]> granicus.if.org Git - esp-idf/commitdiff
Merge branch 'feature/ci_host_test_tag' into 'master'
authorAngus Gratton <angus@espressif.com>
Thu, 7 Jun 2018 03:59:25 +0000 (11:59 +0800)
committerAngus Gratton <angus@espressif.com>
Thu, 7 Jun 2018 03:59:25 +0000 (11:59 +0800)
ci: Use new common host_test tag for host-side testing

See merge request idf/esp-idf!2514

21 files changed:
components/bt/Kconfig
components/bt/bluedroid/bta/dm/bta_dm_act.c
components/bt/bluedroid/bta/gatt/bta_gattc_act.c
components/bt/bluedroid/bta/gatt/bta_gattc_api.c
components/bt/bluedroid/bta/gatt/bta_gattc_cache.c
components/bt/bluedroid/bta/gatt/bta_gattc_co.c
components/bt/bluedroid/bta/include/bta/bta_gatt_api.h
components/bt/bluedroid/bta/include/bta/bta_gattc_co.h
components/bt/bluedroid/btc/profile/std/gatt/btc_gattc.c
components/bt/bluedroid/common/include/common/bt_target.h
components/bt/include/esp_bt.h
components/idf_test/integration_test/INIT_COND_SSC.yml
components/idf_test/integration_test/TC_IT_BTSTK_GATT.yml
components/lwip/core/tcp.c
components/newlib/time.c
docs/en/api-guides/blufi.rst [new file with mode: 0644]
docs/en/api-guides/index.rst
docs/en/api-guides/wifi.rst
docs/en/security/flash-encryption.rst
docs/zh_CN/api-guides/blufi.rst [new file with mode: 0644]
docs/zh_CN/api-guides/index.rst

index 33bd87112131f2fed3b8282c07df8ffcb90829c1..7f5c0b3a7dafa06a83a92ca014dfa8e9256f6a28 100644 (file)
@@ -220,6 +220,13 @@ config GATTC_ENABLE
     help
         This option can be close when the app work only on gatt server mode
 
+config GATTC_CACHE_NVS_FLASH
+    bool "Save gattc cache data to nvs flash"
+    depends on GATTC_ENABLE
+    default n
+    help
+        This select can save gattc cache data to nvs flash
+
 config BLE_SMP_ENABLE
    bool "Include BLE security module(SMP)"
    depends on BLUEDROID_ENABLED
index caa4943145e9504dea81a206792672c4741042f0..5e84d7daa041d44b25fa9772b9ec0f571f63ed9a 100644 (file)
@@ -374,6 +374,12 @@ static void bta_dm_sys_hw_cback( tBTA_SYS_HW_EVT status )
         bta_sys_hw_unregister( BTA_SYS_HW_BLUETOOTH );
         /* notify BTA DM is now unactive */
         bta_dm_cb.is_bta_dm_active = FALSE;
+#if (defined BLE_INCLUDED && BLE_INCLUDED == TRUE)
+#if (GATTC_INCLUDED == TRUE && GATTC_CACHE_NVS == TRUE)
+        /* clear the gattc cache address list */
+        bta_gattc_co_cache_addr_deinit();
+#endif
+#endif
     } else if ( status == BTA_SYS_HW_ON_EVT ) {
         /* FIXME: We should not unregister as the SYS shall invoke this callback on a H/W error.
         * We need to revisit when this platform has more than one BLuetooth H/W chip */
@@ -403,7 +409,7 @@ static void bta_dm_sys_hw_cback( tBTA_SYS_HW_EVT status )
         BTM_SetDeviceClass (dev_class);
 
 #if (defined BLE_INCLUDED && BLE_INCLUDED == TRUE)
-#if (GATTC_INCLUDED == TRUE)
+#if (GATTC_INCLUDED == TRUE && GATTC_CACHE_NVS == TRUE)
         // load the gattc cache address list
         bta_gattc_co_cache_addr_init();
 #endif /* #if (GATTC_INCLUDED = TRUE) */
@@ -703,7 +709,7 @@ void bta_dm_process_remove_device(BD_ADDR bd_addr)
 
 #if (BLE_INCLUDED == TRUE && GATTC_INCLUDED == TRUE)
     /* remove all cached GATT information */
-    BTA_GATTC_Refresh(bd_addr);
+    BTA_GATTC_Refresh(bd_addr, false);
 #endif
 
     if (bta_dm_cb.p_sec_cback) {
@@ -887,7 +893,7 @@ void bta_dm_close_acl(tBTA_DM_MSG *p_data)
         /* need to remove all pending background connection if any */
         BTA_GATTC_CancelOpen(0, p_remove_acl->bd_addr, FALSE);
         /* remove all cached GATT information */
-        BTA_GATTC_Refresh(p_remove_acl->bd_addr);
+        BTA_GATTC_Refresh(p_remove_acl->bd_addr, false);
 #endif
     }
     /* otherwise, no action needed */
@@ -3336,7 +3342,7 @@ void bta_dm_acl_change(tBTA_DM_MSG *p_data)
             /* need to remove all pending background connection */
             BTA_GATTC_CancelOpen(0, p_bda, FALSE);
             /* remove all cached GATT information */
-            BTA_GATTC_Refresh(p_bda);
+            BTA_GATTC_Refresh(p_bda, false);
 #endif
         }
 
@@ -3510,7 +3516,7 @@ static void bta_dm_remove_sec_dev_entry(BD_ADDR remote_bd_addr)
         /* need to remove all pending background connection */
         BTA_GATTC_CancelOpen(0, remote_bd_addr, FALSE);
         /* remove all cached GATT information */
-        BTA_GATTC_Refresh(remote_bd_addr);
+        BTA_GATTC_Refresh(remote_bd_addr, false);
 #endif
     }
 }
index e836003dd4f54af98ad7773fcfa66ede3e328435..eaca767d6ae84be33099b2e4d30ab42efb61a561 100644 (file)
@@ -65,6 +65,7 @@ static void bta_gattc_pop_command_to_send(tBTA_GATTC_CLCB *p_clcb);
 static void bta_gattc_deregister_cmpl(tBTA_GATTC_RCB *p_clreg);
 static void bta_gattc_enc_cmpl_cback(tGATT_IF gattc_if, BD_ADDR bda);
 static void bta_gattc_cong_cback (UINT16 conn_id, BOOLEAN congested);
+static void bta_gattc_req_cback (UINT16 conn_id, UINT32 trans_id, tGATTS_REQ_TYPE type, tGATTS_DATA *p_data);
 static tBTA_GATTC_FIND_SERVICE_CB bta_gattc_register_service_change_notify(UINT16 conn_id, BD_ADDR remote_bda);
 
 static tGATT_CBACK bta_gattc_cl_cback = {
@@ -72,7 +73,7 @@ static tGATT_CBACK bta_gattc_cl_cback = {
     bta_gattc_cmpl_cback,
     bta_gattc_disc_res_cback,
     bta_gattc_disc_cmpl_cback,
-    NULL,
+    bta_gattc_req_cback,
     bta_gattc_enc_cmpl_cback,
     bta_gattc_cong_cback
 };
@@ -666,11 +667,14 @@ void bta_gattc_conn(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data)
     if (p_clcb->p_srcb->p_srvc_cache == NULL ||
             p_clcb->p_srcb->state != BTA_GATTC_SERV_IDLE) {
         if (p_clcb->p_srcb->state == BTA_GATTC_SERV_IDLE) {
+#if (GATTC_CACHE_NVS == TRUE)
             p_clcb->p_srcb->state = BTA_GATTC_SERV_LOAD;
             if (bta_gattc_cache_load(p_clcb)) {
                 p_clcb->p_srcb->state = BTA_GATTC_SERV_IDLE;
                 bta_gattc_reset_discover_st(p_clcb->p_srcb, BTA_GATT_OK);
-            } else { /* cache is building */
+            } else 
+#endif
+            { /* cache is building */
                 p_clcb->p_srcb->state = BTA_GATTC_SERV_DISC;
                 /* cache load failure, start discovery */
                 bta_gattc_start_discover(p_clcb, NULL);
@@ -1016,9 +1020,10 @@ void bta_gattc_disc_cmpl(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data)
             list_free(p_clcb->p_srcb->p_srvc_cache);
             p_clcb->p_srcb->p_srvc_cache = NULL;
         }
-
+#if(GATTC_CACHE_NVS == TRUE)
         /* used to reset cache in application */
         bta_gattc_cache_reset(p_clcb->p_srcb->server_bda);
+#endif
     }
     if (p_clcb->p_srcb && p_clcb->p_srcb->p_srvc_list) {
         /* release pending attribute list buffer */
@@ -1716,7 +1721,6 @@ void bta_gattc_process_api_refresh(tBTA_GATTC_CB *p_cb, tBTA_GATTC_DATA *p_msg)
             }
             if (found) {
                 bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_DISCOVER_EVT, NULL);
-                bta_gattc_cache_reset(p_msg->api_conn.remote_bda);
                 return;
             }
         }
@@ -1726,8 +1730,6 @@ void bta_gattc_process_api_refresh(tBTA_GATTC_CB *p_cb, tBTA_GATTC_DATA *p_msg)
             p_srvc_cb->p_srvc_cache = NULL;
         }
     }
-    /* used to reset cache in application */
-    bta_gattc_cache_reset(p_msg->api_conn.remote_bda);
 }
 
 void bta_gattc_process_api_cache_assoc(tBTA_GATTC_CB *p_cb, tBTA_GATTC_DATA *p_msg)
@@ -2085,6 +2087,27 @@ static void bta_gattc_cong_cback (UINT16 conn_id, BOOLEAN congested)
     }
 }
 
+/*******************************************************************************
+**
+** Function         bta_gattc_req_cback
+**
+** Description      GATT request command callback for BTA GATT client.
+**
+** Returns          void
+**
+********************************************************************************/
+static void bta_gattc_req_cback (UINT16 conn_id, UINT32 trans_id, tGATTS_REQ_TYPE type, tGATTS_DATA *p_data)
+{
+    /* GATTC doesn't need to process the GATT request commands.
+     * Add this callback here to avoid the warning "Call back not found for application"
+     * printed in the function gatt_sr_send_req_callback
+     * */
+    UNUSED (conn_id);
+    UNUSED (trans_id) ;
+    UNUSED (type);
+    UNUSED (p_data);
+}
+
 #if BLE_INCLUDED == TRUE
 /*******************************************************************************
 **
index b7c292a51e396cb8ff58675565ea630f82224573..45a155e1e6c38cf758641bbb9abc5727f248f7aa 100644 (file)
@@ -912,12 +912,20 @@ tBTA_GATT_STATUS BTA_GATTC_DeregisterForNotifications (tBTA_GATTC_IF client_if,
 ** Description      Refresh the server cache of the remote device
 **
 ** Parameters       remote_bda: remote device BD address.
+**                  erase_flash: delete cache from nvs flash
 **
 ** Returns          void
 **
 *******************************************************************************/
-void BTA_GATTC_Refresh(BD_ADDR remote_bda)
+void BTA_GATTC_Refresh(BD_ADDR remote_bda, bool erase_flash)
 {
+#if(GATTC_CACHE_NVS == TRUE)
+    if(erase_flash) {
+        /* used to reset cache in application */
+        bta_gattc_cache_reset(remote_bda);
+    }
+#endif
+
     tBTA_GATTC_API_OPEN  *p_buf;
 
     if ((p_buf = (tBTA_GATTC_API_OPEN *) osi_malloc(sizeof(tBTA_GATTC_API_OPEN))) != NULL) {
index 8a5625356ca2a97ccc4785a102c2ff77d0103830..66d3bb8becf87cdc449047c6d687910e9129d244 100644 (file)
@@ -622,10 +622,11 @@ static void bta_gattc_explore_srvc(UINT16 conn_id, tBTA_GATTC_SERV *p_srvc_cb)
         L2CA_EnableUpdateBleConnParams(p_clcb->p_srcb->server_bda, TRUE);
     }
 #endif
+#if(GATTC_CACHE_NVS == TRUE)
     /* save cache to NV */
     p_clcb->p_srcb->state = BTA_GATTC_SERV_SAVE;
-
     bta_gattc_cache_save(p_clcb->p_srcb, p_clcb->bta_conn_id);
+#endif
     bta_gattc_reset_discover_st(p_clcb->p_srcb, BTA_GATT_OK);
 }
 /*******************************************************************************
index 6c6fc460d3f74350a6d02843334bd1d2220383bb..1a1599af55f03743598ba9ad4a5c4062d3cfe678 100644 (file)
@@ -75,7 +75,7 @@ static void cacheReset(BD_ADDR bda)
 
 #else
 
-static const char *cache_key = "gattc_cahe_key";
+static const char *cache_key = "gattc_cache_key";
 static const char *cache_addr = "cache_addr_tab";
 nvs_handle nvs_fp;
 
@@ -144,7 +144,7 @@ static void cacheReset(BD_ADDR bda)
     char fname[255] = {0};
     getFilename(fname, bda);
     UINT8 index = 0;
-      //cache_env.cache_addr
+    //cache_env.cache_addr
     if ((index = bta_gattc_co_find_addr_in_cache(bda)) != INVALID_ADDR_NUM) {
         //clear the association address pending in the source address.
         bta_gattc_co_cache_clear_assoc_addr(bda);
@@ -152,7 +152,22 @@ static void cacheReset(BD_ADDR bda)
             nvs_erase_all(cache_env.cache_addr[index].cache_fp);
             nvs_close(cache_env.cache_addr[index].cache_fp);
             cache_env.cache_addr[index].is_open = FALSE;
+        } else {
+            cacheOpen(bda, false, &index);
+            if (cache_env.cache_addr[index].is_open) {
+                nvs_erase_all(cache_env.cache_addr[index].cache_fp);
+                nvs_close(cache_env.cache_addr[index].cache_fp);
+                cache_env.cache_addr[index].is_open = FALSE;
+            } else {
+                APPL_TRACE_ERROR("%s cacheOpen failed", __func__);
+                return;
+            }
+        }
+        if(cache_env.num_addr == 0) {
+            APPL_TRACE_ERROR("%s cache addr list error", __func__);
+            return;
         }
+
         UINT8 num = cache_env.num_addr;
         //delete the server_bda in the addr_info list.
         for(UINT8 i = index; i < (num - 1); i++) {
@@ -160,6 +175,40 @@ static void cacheReset(BD_ADDR bda)
         }
         //reduced the number address counter also
         cache_env.num_addr--;
+
+        //update addr list to nvs flash
+        if(cache_env.num_addr > 0) {
+            //update
+            UINT8 *p_buf = osi_malloc(MAX_ADDR_LIST_CACHE_BUF);
+            if(!p_buf) {
+                APPL_TRACE_ERROR("%s malloc error", __func__); 
+                return;  
+            }
+            UINT16 length = cache_env.num_addr*(sizeof(BD_ADDR) + sizeof(hash_key_t));
+            for (UINT8 i = 0; i < cache_env.num_addr; i++) {
+                //copy the address to the buffer.
+                memcpy(p_buf + i*(sizeof(BD_ADDR) + sizeof(hash_key_t)), cache_env.cache_addr[i].addr, sizeof(BD_ADDR));
+                //copy the hash key to the buffer.
+                memcpy(p_buf + i*(sizeof(BD_ADDR) + sizeof(hash_key_t)) + sizeof(BD_ADDR),
+                        cache_env.cache_addr[i].hash_key, sizeof(hash_key_t));
+            }
+            if (cache_env.is_open) {
+                if (nvs_set_blob(cache_env.addr_fp, cache_key, p_buf, length) != ESP_OK) {
+                    APPL_TRACE_WARNING("%s, nvs set blob failed", __func__);
+                }
+            }
+            osi_free(p_buf);
+        
+        } else {
+            //erase
+            if (cache_env.is_open) {
+                nvs_erase_all(cache_env.addr_fp);
+                nvs_close(cache_env.addr_fp);
+                cache_env.is_open = FALSE;
+            } else {
+                APPL_TRACE_WARNING("cache_env status is error");
+            }
+        }
     }
 }
 
@@ -325,10 +374,11 @@ void bta_gattc_co_cache_addr_init(void)
     esp_err_t err_code;
     UINT8 num_addr;
     UINT8 *p_buf = osi_malloc(MAX_ADDR_LIST_CACHE_BUF);
-    size_t length = 0;
+    size_t length = MAX_ADDR_LIST_CACHE_BUF;
 
     if ((err_code = nvs_open(cache_addr, NVS_READWRITE, &fp)) == ESP_OK) {
         cache_env.addr_fp = fp;
+        cache_env.is_open = TRUE;
         // Read previously saved blob if available
         if ((err_code = nvs_get_blob(fp, cache_key, p_buf, &length)) != ESP_OK) {
             if(err_code != ESP_ERR_NVS_NOT_FOUND) {
@@ -361,6 +411,26 @@ void bta_gattc_co_cache_addr_init(void)
     return;
 }
 
+void bta_gattc_co_cache_addr_deinit(void)
+{
+    if(!cache_env.is_open) {
+        return;
+    }  
+    nvs_close(cache_env.addr_fp);
+    cache_env.is_open = false;
+    
+    for(UINT8 i = 0; i< cache_env.num_addr; i++) {
+        cache_addr_info_t *addr_info = &cache_env.cache_addr[i];
+        if(addr_info) {
+            nvs_close(addr_info->cache_fp);
+            addr_info->is_open = false;
+            if(addr_info->assoc_addr) {
+                list_free(addr_info->assoc_addr);
+            }
+        }
+    }
+}
+
 BOOLEAN bta_gattc_co_addr_in_cache(BD_ADDR bda)
 {
     UINT8 addr_index = 0;
index 72eb3643b6637583d3c3ce298f207a05224cf888..723c7fe26b9c7b6d739426f858ac24168cf3289a 100644 (file)
@@ -1096,11 +1096,12 @@ extern void BTA_GATTC_ReadMultiple(UINT16 conn_id, tBTA_GATTC_MULTI *p_read_mult
 ** Description      Refresh the server cache of the remote device
 **
 ** Parameters       remote_bda: remote device BD address.
+**                  erase_flash: delete cache from nvs flash
 **
 ** Returns          void
 **
 *******************************************************************************/
-extern void BTA_GATTC_Refresh(BD_ADDR remote_bda);
+extern void BTA_GATTC_Refresh(BD_ADDR remote_bda, bool erase_flash);
 
 extern void BTA_GATTC_CacheAssoc(tBTA_GATTC_IF client_if, BD_ADDR src_addr, BD_ADDR assoc_addr, BOOLEAN is_assoc);
 
index a902a2edf2eb1af725324b92018345406b689258..44a0e18ef204313ba841a49178d5be46b3269eba 100644 (file)
@@ -113,6 +113,8 @@ extern size_t bta_gattc_get_cache_attr_length(UINT8 index);
 
 extern void bta_gattc_co_cache_addr_init(void);
 
+extern void bta_gattc_co_cache_addr_deinit(void);
+
 extern BOOLEAN bta_gattc_co_addr_in_cache(BD_ADDR bda);
 
 extern uint8_t bta_gattc_co_find_addr_in_cache(BD_ADDR bda);
index 0694b990f00524895e7e2c2052cd6dc1ece54f1a..d48cd0b40b21ef31f1a290dd965b97316664e637 100644 (file)
@@ -738,7 +738,7 @@ void btc_gattc_call_handler(btc_msg_t *msg)
         btc_gattc_unreg_for_notify(arg);
         break;
     case BTC_GATTC_ACT_CACHE_REFRESH:
-        BTA_GATTC_Refresh(arg->cache_refresh.remote_bda);
+        BTA_GATTC_Refresh(arg->cache_refresh.remote_bda, true);
         break;
     case BTC_GATTC_ACT_CACHE_ASSOC:
         BTA_GATTC_CacheAssoc(arg->cache_assoc.gattc_if,
index fc12bde071770d3755a553e135685bac92c1e7d1..ef45566867b7266eb847e0de02ede60bc92a86e7 100644 (file)
 #define CLASSIC_BT_INCLUDED         FALSE
 #endif /* CLASSIC_BT_INCLUDED */
 
+#ifndef CONFIG_GATTC_CACHE_NVS_FLASH
+#define CONFIG_GATTC_CACHE_NVS_FLASH         FALSE
+#endif /* CONFIG_GATTC_CACHE_NVS_FLASH */
+
 /******************************************************************************
 **
 ** BLE features
 #define GATTC_INCLUDED              FALSE
 #endif  /* CONFIG_GATTC_ENABLE */
 
+#if (CONFIG_GATTC_ENABLE && CONFIG_GATTC_CACHE_NVS_FLASH)
+#define GATTC_CACHE_NVS              TRUE
+#else
+#define GATTC_CACHE_NVS              FALSE
+#endif  /* CONFIG_GATTC_CACHE_NVS_FLASH */
+
 #if (CONFIG_SMP_ENABLE)
 #define SMP_INCLUDED              TRUE
 #define BLE_PRIVACY_SPT           TRUE
index 28aa3cbdfbab37d8518a824551cb2cb780999f4a..9b599f428d0fa6c3592d570c76be6f789fa024a4 100644 (file)
@@ -291,7 +291,7 @@ void esp_vhci_host_register_callback(const esp_vhci_host_callback_t *callback);
 
 /** @brief esp_bt_controller_mem_release
  * release the memory by mode, if never use the bluetooth mode
- * it can release the .bbs, .data and other section to heap.
+ * it can release the .bss, .data and other section to heap.
  * The total size is about 70k bytes.
  *
  * esp_bt_controller_mem_release(mode) should be called only before esp_bt_controller_init()
index d143bf02a0dea5de58f603a80c057d5195cdc938..797e4445c67bebc92de06e64ba6db74bc2f014d2 100644 (file)
@@ -355,11 +355,11 @@ initial condition:
     - - R SSC2 C +BLEADV:OK
   - - SSC SSC2 gatts -S -z load -p 0xA0
     - - R SSC2 C +GATTS:StartService,OK,A000
+  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
+    - - R SSC1 C +GATTC:OK
   - - SSC SSC1 bleconn -C -p 0x10 -a <dut2_bt_mac>
     - - R SSC1 C +BLE:GattcConnect,OK
       - P SSC2 C +BLE:GattsConnect
-  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
-    - - R SSC1 C +GATTC:OK
   force restore cmd set:
   - ''
   - - SSC SSC[1-2] reboot
@@ -383,11 +383,11 @@ initial condition:
     - - R SSC2 C +BLEADV:OK
   - - SSC SSC2 gatts -S -z load -p 0xA0
     - - R SSC2 C +GATTS:StartService,OK,A000
+  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
+    - - R SSC1 C +GATTC:OK
   - - SSC SSC1 bleconn -C -p 0x10 -a <dut2_bt_mac>
     - - R SSC1 C +BLE:GattcConnect,OK
       - P SSC2 C +BLE:GattsConnect
-  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
-    - - R SSC1 C +GATTC:OK
   restore post cmd set:
   - ''
   - - SSC SSC1 ram
@@ -425,11 +425,11 @@ initial condition:
     - - R SSC2 C +BLEADV:OK
   - - SSC SSC2 gatts -S -z load -p 0xA2
     - - R SSC2 C +GATTS:StartService,OK,A002
+  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
+    - - R SSC1 C +GATTC:OK
   - - SSC SSC1 bleconn -C -p 0x10 -a <dut2_bt_mac>
     - - R SSC1 C +BLE:GattcConnect,OK
       - P SSC2 C +BLE:GattsConnect
-  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
-    - - R SSC1 C +GATTC:OK
   force restore cmd set:
   - ''
   - - SSC SSC[1-2] reboot
@@ -453,11 +453,11 @@ initial condition:
     - - R SSC2 C +BLEADV:OK
   - - SSC SSC2 gatts -S -z load -p 0xA2
     - - R SSC2 C +GATTS:StartService,OK,A002
+  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
+    - - R SSC1 C +GATTC:OK
   - - SSC SSC1 bleconn -C -p 0x10 -a <dut2_bt_mac>
     - - R SSC1 C +BLE:GattcConnect,OK
       - P SSC2 C +BLE:GattsConnect
-  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
-    - - R SSC1 C +GATTC:OK
   restore post cmd set:
   - ''
   - - SSC SSC1 ram
@@ -495,13 +495,13 @@ initial condition:
     - - R SSC2 C +BLEADV:OK
   - - SSC SSC[1-2] gatts -S -z load -p 0xA2
     - - R SSC[1-2] C +GATTS:StartService,OK,A002
+  - - SSC SSC[1-2] gattc -F -r <dut[2,1]_bt_mac>
+    - - R SSC[1-2] C +GATTC:OK
   - - SSC SSC1 bleconn -C -p 0x10 -a <dut2_bt_mac>
     - - R SSC1 C +BLE:GattcConnect,OK
       - P SSC2 C +BLE:GattsConnect
   - - SSC SSC2 bleconn -C -p 0x10 -a <dut1_bt_mac>
     - - R SSC2 C +BLE:GattcOpen,OK
-  - - SSC SSC[1-2] gattc -F -r <dut[2-1]_bt_mac>
-    - - R SSC[1-2] C +GATTC:OK
   force restore cmd set:
   - ''
   - - SSC SSC[1-2] reboot
@@ -525,13 +525,13 @@ initial condition:
     - - R SSC2 C +BLEADV:OK
   - - SSC SSC[1-2] gatts -S -z load -p 0xA2
     - - R SSC[1-2] C +GATTS:StartService,OK,A002
+  - - SSC SSC[1-2] gattc -F -r <dut[2,1]_bt_mac>
+    - - R SSC[1-2] C +GATTC:OK
   - - SSC SSC1 bleconn -C -p 0x10 -a <dut2_bt_mac>
     - - R SSC1 C +BLE:GattcConnect,OK
       - P SSC2 C +BLE:GattsConnect
   - - SSC SSC2 bleconn -C -p 0x10 -a <dut1_bt_mac>
     - - R SSC2 C +BLE:GattcOpen,OK
-  - - SSC SSC[1-2] gattc -F -r <dut[2-1]_bt_mac>
-    - - R SSC[1-2] C +GATTC:OK
   restore post cmd set:
   - ''
   - - SSC SSC1 ram
@@ -565,6 +565,8 @@ initial condition:
     - - P SSC[2-5] C +BLEADV:Start,OK
   - - SSC SSC[2-5] gatts -S -z load -p 0xA2
     - - P SSC[2-5] C +GATTS:StartService,OK,A002
+  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
+    - - R SSC1 C +GATTC:OK
   - - LOOP 4 1 "[2,3,4,5]" "[2,3,4,5]" "[2,3,4,5]"
     - ''
   - - SSC SSC1 bleconn -C -p 0x10 -a <dut{%d}_bt_mac>
@@ -593,13 +595,13 @@ initial condition:
     - - P SSC[2-5] C +BLEADV:Start,OK
   - - SSC SSC[2-5] gatts -S -z load -p 0xA2
     - - P SSC[2-5] C +GATTS:StartService,OK,A002
+  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
+    - - R SSC1 C +GATTC:OK
   - - LOOP 4 1 "[2,3,4,5]" "[2,3,4,5]" "[2,3,4,5]"
     - ''
   - - SSC SSC1 bleconn -C -p 0x10 -a <dut{%d}_bt_mac>
     - - R SSC1 RE "\+BLE:GattcConnect,OK,0010,%%s"%%(<dut{%d}_bt_mac>)
       - P SSC{%d} C +BLE:GattsConnect
-  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
-    - - R SSC1 C +GATTC:OK
   restore post cmd set:
   - ''
   - - SSC SSC1 ram
@@ -637,11 +639,11 @@ initial condition:
     - ''
   - - SSC SSC1 bleadv -D -z start
     - - P SSC1 C +BLEADV:Start,OK
+  - - SSC SSC[2-5] gattc -F -r <dut1_bt_mac>
+    - - R SSC[2-5] C +GATTC:OK
   - - SSC SSC{%d} bleconn -C -p 0x10 -a <dut1_bt_mac>
     - - R SSC{%d} RE "\+BLE:GattcConnect,OK,0010,%%s"%%(<dut1_bt_mac>)
       - P SSC1 C +BLE:GattsConnect
-  - - SSC SSC[2-5] gattc -F -r <dut1_bt_mac>
-    - - R SSC[2-5] C +GATTC:OK
   force restore cmd set:
   - ''
   - - SSC SSC[1-5] reboot
@@ -661,6 +663,8 @@ initial condition:
     - - R SSC[1-5] C +BLEADV:OK
   - - SSC SSC1 gatts -S -z load -p 0xA2
     - - R SSC1 C +GATTS:StartService,OK,A002
+  - - SSC SSC[2-5] gattc -F -r <dut1_bt_mac>
+    - - R SSC[2-5] C +GATTC:OK
   - - LOOP 4 2 "[2,3,4,5]" "[2,3,4,5]"
     - ''
   - - SSC SSC1 bleadv -D -z start
@@ -668,8 +672,6 @@ initial condition:
   - - SSC SSC{%d} bleconn -C -p 0x10 -a <dut1_bt_mac>
     - - R SSC{%d} RE "\+BLE:GattcConnect,OK,0010,%%s"%%(<dut1_bt_mac>)
       - P SSC1 C +BLE:GattsConnect
-  - - SSC SSC[2-5] gattc -F -r <dut1_bt_mac>
-    - - R SSC[2-5] C +GATTC:OK
   restore post cmd set:
   - ''
   - - SSC SSC1 ram
@@ -1045,6 +1047,8 @@ initial condition:
     - ["P SSC[2-5] C +GATTS:StartService,OK,A000"]
   - - SSC SSC[1-5] bleadv -D -z stop
     - - R SSC[1-5] C +BLEADV:OK
+  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
+    - - R SSC1 C +GATTC:OK
   - - SSC SSC1 ram
     - - R SSC1 A <heap_size>:(\d+)
 - tag: BLE_INIT_SMP
@@ -1084,6 +1088,8 @@ initial condition:
     - - R SSC2 C +BLEADV:OK
   - - SSC SSC[1-2] blesmp -L -c [1,0]
     - - R SSC[1-2] C +BLESMP:OK
+  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
+    - - R SSC1 C +GATTC:OK
   - - SSC SSC1 ram
     - - R SSC1 A <heap_size>:(\d+)
   restore post cmd set:
@@ -1111,6 +1117,8 @@ initial condition:
     - - R SSC2 C +BLEADV:OK
   - - SSC SSC[1-2] blesmp -L -c [1,0]
     - - R SSC[1-2] C +BLESMP:OK
+  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
+    - - R SSC1 C +GATTC:OK
   - - SSC SSC1 ram
     - - R SSC1 A <heap_size>:(\d+)
 - tag: BLE_INIT_SMP5
@@ -1150,6 +1158,8 @@ initial condition:
     - - R SSC[2-5] C +BLEADV:OK
   - - SSC SSC[1-5] blesmp -L -c [1,0]
     - - R SSC[1-5] C +BLESMP:OK
+  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
+    - - R SSC1 C +GATTC:OK
   restore post cmd set:
   - ''
   - - SSC SSC[1-5] ble -R
@@ -1175,6 +1185,8 @@ initial condition:
   # do wifi disconnect, to prevent wifi reconnect cause bad BLE performance
   - - SSC SSC[1-5] sta -D
     - []
+  - - SSC SSC1 gattc -F -r <dut2_bt_mac>
+    - - R SSC1 C +GATTC:OK
   - - SSC SSC1 ram
     - - R SSC1 A <heap_size>:(\d+)
 - tag: NOW1
index 6e153fb58af6e5426c3568886563fb8132ad4196..f1a88881d1d1e52ed726db95707690f6e8a97433 100644 (file)
@@ -304,6 +304,7 @@ test cases:
   initial condition: BLE_CONN3
   cmd set:
   - ""
+  - *primary_service_discovery
   - - "SSC SSC2 gatts -V -c 0xC300 -p 0xA2 -z set -v 0x02"
     - ["R SSC2 C +GATTS:SetAttrVal,OK"]
   - - "SSC SSC1 gattc -R -z char -s 0xA002 -c 0xC300 -p 0x10"
@@ -499,6 +500,7 @@ test cases:
   initial condition: BLE_CONN3
   cmd set:
   - ""
+  - *primary_service_discovery
   - - "SSC SSC2 gatts -V -c 0xC300 -d 0x2901 -p 0xA2 -z set -v 0x02"
     - ["R SSC2 C +GATTS:SetAttrVal,OK"]
   - - "SSC SSC1 gattc -R -z descriptor -s 0xA002 -c 0xC300 -d 0x2901 -p 0x10"
index 920523e45d603f6015821412734aad8aba52fd23..35649f12fa55fc015211ad680238deaf54875486 100644 (file)
@@ -1751,19 +1751,31 @@ tcp_pcb_purge(struct tcp_pcb *pcb)
     if (pcb->state == SYN_RCVD) {
       /* Need to find the corresponding listen_pcb and decrease its accepts_pending */
       struct tcp_pcb_listen *lpcb;
-      LWIP_ASSERT("tcp_pcb_purge: pcb->state == SYN_RCVD but tcp_listen_pcbs is NULL",
-        tcp_listen_pcbs.listen_pcbs != NULL);
-      for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
-        if ((lpcb->local_port == pcb->local_port) &&
-            (IP_IS_V6_VAL(pcb->local_ip) == IP_IS_V6_VAL(lpcb->local_ip)) &&
-            (ip_addr_isany(&lpcb->local_ip) ||
-             ip_addr_cmp(&pcb->local_ip, &lpcb->local_ip))) {
-            /* port and address of the listen pcb match the timed-out pcb */
-            LWIP_ASSERT("tcp_pcb_purge: listen pcb does not have accepts pending",
-              lpcb->accepts_pending > 0);
-            lpcb->accepts_pending--;
-            break;
+
+      /*
+       * The official LWIP will assert the system if tcp_listen_pcbs.listen_pcbs is NULL, it's a bug.
+       *
+       * Considering following scenario:
+       * 1. On TCP server side, one of TCP pcb is in SYNC_RECV state and is waiting for TCP ACK from TCP client.
+       * 2. The TCP server is closed by application, which causes the tcp_listen_pcbs.listen_pcbs to become NULL.
+       * 3. When SYNC_RECV state timeout (20s by default), tcp_pcb_purge() is called in tcp_slowtmr(), it asserts
+       *    the system.
+       * This is a normal scenario, should NOT assert the system. So just remove it.
+       * 
+       */
+      if (tcp_listen_pcbs.listen_pcbs) {
+        for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
+          if ((lpcb->local_port == pcb->local_port) &&
+              (IP_IS_V6_VAL(pcb->local_ip) == IP_IS_V6_VAL(lpcb->local_ip)) &&
+              (ip_addr_isany(&lpcb->local_ip) ||
+               ip_addr_cmp(&pcb->local_ip, &lpcb->local_ip))) {
+              /* port and address of the listen pcb match the timed-out pcb */
+              LWIP_ASSERT("tcp_pcb_purge: listen pcb does not have accepts pending",
+                lpcb->accepts_pending > 0);
+              lpcb->accepts_pending--;
+              break;
           }
+        }
       }
     }
 #endif /* TCP_LISTEN_BACKLOG */
index 37b78f3de58f972795b87b04e72cfe8fb385b7f4..d40dc57397014d62305be318db7c22d3f9841ed3 100644 (file)
@@ -80,9 +80,9 @@ static uint64_t s_boot_time;
 static _lock_t s_boot_time_lock;
 static _lock_t s_adjust_time_lock;
 // stores the start time of the slew
-RTC_DATA_ATTR static uint64_t adjtime_start = 0;
+static uint64_t adjtime_start = 0;
 // is how many microseconds total to slew
-RTC_DATA_ATTR static int64_t adjtime_total_correction = 0;
+static int64_t adjtime_total_correction = 0;
 #define ADJTIME_CORRECTION_FACTOR 6
 static uint64_t get_time_since_boot();
 #endif
diff --git a/docs/en/api-guides/blufi.rst b/docs/en/api-guides/blufi.rst
new file mode 100644 (file)
index 0000000..429c5d9
--- /dev/null
@@ -0,0 +1,431 @@
+BluFi
+^^^^^
+
+Overview
+--------
+The BluFi for ESP32 is a Wi-Fi network configuration function via Bluetooth channel. It provides a secure protocol to pass Wi-Fi configuration and credentials to the ESP32. Using this information ESP32 can then e.g. connect to an AP or establish a SoftAP.
+
+Fragmenting, data encryption, checksum verification in the BluFi layer are the key elements of this process.
+
+You can customize symmetric encryption, asymmetric encryption and checksum support customization. Here we use the DH algorithm for key negotiation, 128-AES algorithm for data encryption, and CRC16 algorithm for checksum verification.
+
+The BluFi Flow
+---------------
+The BluFi networking flow includes the configuration of the SoftAP and Station.
+
+The following uses Station as an example to illustrate the core parts of the procedure, including broadcast, connection, service discovery, negotiation of the shared key, data transmission, connection status backhaul.
+
+1. Set the ESP32 into GATT Server mode and then it will send broadcasts with specific *advertising data*. You can customize this broadcast as needed, which is not a part of the BluFi Profile.
+
+2. Use the App installed on the mobile phone to search for this particular broadcast. The mobile phone will connect to ESP32 as the GATT Client once the broadcast is confirmed. The App used during this part is up to you.
+
+3. After the GATT connection is successfully established, the mobile phone will send a data frame for key negotiation to ESP32 (see the section :ref:`frame_formats` for details).
+
+4. After ESP32 receives the data frame of key negotiation, it will parse the content according to the user-defined negotiation method.
+
+5. The mobile phone works with ESP32 for key negotiation using the encryption algorithms such as DH, RSA or ECC.
+
+6. After the negotiation process is completed, the mobile phone will send a control frame for security-mode setup to ESP32.
+
+7. When receiving this control frame, ESP32 will be able to encrypt and decrypt the communication data using the shared key and the security configuration.
+
+8. The mobile phone sends the data frame defined in the section of :ref:`frame_formats`,with the Wi-Fi configuration information to ESP32, including SSID, password, etc.
+
+9. The mobile phone sends a control frame of Wi-Fi connection request to ESP32. When receiving this control frame, ESP32 will regard the communication of essential information as done and get ready to connect to the Wi-Fi.
+
+10. After connecting to the Wi-Fi, ESP32 will send a control frame of Wi-Fi connection status report to the mobile phone,to report the connection status. At this point the networking procedure is completed.
+
+.. note::
+
+    1. After ESP32 receives the control frame of security-mode configuration, it will execute the operations in accordance with the defined security mode.
+
+    2. The data lengths before and after symmetric encryption/decryption must stay the same. It also supports in-place encryption and decryption.
+
+The flow chat of BluFi
+-----------------------
+
+.. seqdiag::
+    :caption: BluFi Flow Chart
+    :align: center
+
+    seqdiag blufi {
+        activation = none;
+        node_width = 80;
+        node_height = 60;
+        edge_length = 380;
+        span_height = 10;
+        default_fontsize = 12; 
+
+        Phone <- ESP32 [label="Advertising"];
+        Phone -> ESP32 [label="Create GATT connection"];
+        Phone <- ESP32 [label="Negotiate key procedure"];
+        Phone -> ESP32 [label="Negotiate key procedure"];
+        Phone -> ESP32 [label="CTRL: Set ESP32 to Phone Security mode"];
+        Phone -> ESP32 [label="DATA: SSID"];
+        Phone -> ESP32 [label="DATA: Password"];
+        Phone -> ESP32 [label="DATA: Other information, such as CA certification"];
+        Phone -> ESP32 [label="CTRL: Connect to AP"];
+        Phone <- ESP32 [label="DATA: Connection State Report"];
+    }
+
+.. _frame_formats:
+
+The Frame Formats Defined in BluFi
+-----------------------------------
+
+The frame formats for the communication between the mobile phone App and ESP32 are defined as follows:
+
+The frame format with no fragment (8 bit):
+
++------------+---------------+-----------------+-------------+----------------+----------------+
+| LSB - Type | Frame Control | Sequence Number | Data Length | Data           | MSB - CheckSum |
++============+===============+=================+=============+================+================+
+| 1          | 1             | 1               | 1           | ${Data Length} | 2              |
++------------+---------------+-----------------+-------------+----------------+----------------+
+
+If the **Frame Ctrl** bit is enabled, the **Total length** bit indicates the length of remaining part of the frame. It can tell the remote how much memory needs to be alloced.
+
+The frame format with fragments(8 bit):
+
++------------+--------------------+----------------+------------+-------------------------------------------+----------------+
+| LSB - Type | FrameControl(Frag) | SequenceNumber | DataLength |                    Data                   | MSB - CheckSum |
++            +                    +                +            +----------------------+--------------------+                +
+|            |                    |                |            | Total Content Length |       Content      |                |
++============+====================+================+============+======================+====================+================+
+|      1     |          1         |        1       |      1     |           2          | ${Data Length} - 2 |        2       |
++------------+--------------------+----------------+------------+----------------------+--------------------+----------------+
+
+Normally, the control frame does not contain data bits, except for Ack Frame.
+
+The format of Ack Frame(8 bit):
+
++------------------+----------------+------------------+--------------+-----------------------+----------------+
+| LSB - Type (Ack) | Frame Control  | SequenceNumber   | Data Length  | Data                  | MSB - CheckSum |
++                  +                +                  +              +-----------------------+                +
+|                  |                |                  |              | Acked Sequence Number |                |
++==================+================+==================+==============+=======================+================+
+| 1                | 1              | 1                | 1            | 1                     | 2              |
++------------------+----------------+------------------+--------------+-----------------------+----------------+
+
+1. Type
+
+   The **Type** field, taking 1 byte, is divided into **Type** and **Subtype**, that Type uses the lower 2 bits and **Subtype** uses the upper 6 bits.
+
+   * The control frame is not encrypted for the time being and supports to be verified;
+
+   * The data frame supports to be encrypted and verified.
+   
+ **1.1 Control Frame (0x0b’00)**  
+
+  +-------------------------+--------------------------------------------------------------+---------------------------------------------------------------+---------------------------------------------------------------+
+  | Control Frame / 0x0b’00 | Implication                                                  | Explanation                                                   | Note                                                          |
+  +=========================+==============================================================+===============================================================+===============================================================+
+  | 0x0b’000000             | Ack                                                          | The data field of the Ack frame uses the same                 | The data field consumes a byte and its value is               |
+  |                         |                                                              | sequence value of the frame to reply to.                      | the same as the sequence field of the frame to reply to.      |
+  +-------------------------+--------------------------------------------------------------+---------------------------------------------------------------+---------------------------------------------------------------+
+  | 0x1b’000001             | Set ESP32 to the security mode.                              | To inform ESP32 of the security mode to use                   | The data field consumes a byte.                               |
+  |                         |                                                              | when sending data, which is allowed to be reset               | The higher 4 bits are for the security mode setting           |
+  |                         |                                                              | multiple times during the process.                            | of the control frame, and the lower 4 bits are for            |
+  |                         |                                                              | Each setting affects the subsequent security mode used.       | the security mode setting of the data frame.                  |
+  +                         +                                                              + If it is not set, ESP32 will send the control frame           +---------------------------------------------------------------+
+  |                         |                                                              | and data frame with no checksum and encryption by default.    | b’0000: no checksum and no encryption;                        |
+  +                         +                                                              + The data transmission from the mobile phone to ESP32 is       +---------------------------------------------------------------+
+  |                         |                                                              | controlled by this control frame.                             | b’0001: with checksum but no encryption;                      |
+  +                         +                                                              +                                                               +---------------------------------------------------------------+
+  |                         |                                                              |                                                               | b’0010: no checksum but with encryption;                      |
+  +                         +                                                              +                                                               +---------------------------------------------------------------+
+  |                         |                                                              |                                                               | b’0011: with both checksum and encryption.                    |
+  +-------------------------+--------------------------------------------------------------+---------------------------------------------------------------+---------------------------------------------------------------+
+  | 0x2b’000010             | Set the opmode of Wi-Fi.                                     | The frame contains opmode settings for                        | data[0] is for opmode settings, including:                    |
+  +                         +                                                              + configuring for the Wi-Fi mode of ESP32.                      +---------------------------------------------------------------+
+  |                         |                                                              |                                                               | 0x00: NULL;                                                  |
+  +                         +                                                              +                                                               +---------------------------------------------------------------+
+  |                         |                                                              |                                                               | 0x01: STA;                                                    |
+  +                         +                                                              +                                                               +---------------------------------------------------------------+
+  |                         |                                                              |                                                               | 0x02: SoftAP;                                                 |
+  +                         +                                                              +                                                               +---------------------------------------------------------------+
+  |                         |                                                              |                                                               | 0x03: SoftAP&STA.                                             |
+  +                         +                                                              +                                                               +---------------------------------------------------------------+
+  |                         |                                                              |                                                               | Please set the SSID/Password/Max Connection Number of         |
+  |                         |                                                              |                                                               | the AP mode in the first place if an AP gets involved.        |
+  +-------------------------+--------------------------------------------------------------+---------------------------------------------------------------+---------------------------------------------------------------+
+  | 0x3b’000011             | Connect ESP32 to the AP.                                     | To notify ESP32 that the essential information has been sent  | No data field is contained.                                   |
+  |                         |                                                              | and it is allowed to connect to the AP.                       |                                                               |
+  +-------------------------+--------------------------------------------------------------+---------------------------------------------------------------+---------------------------------------------------------------+
+  | 0x4b’000100             | Disconnect ESP32 from the AP.                                |                                                               | No data field is contained.                                   |
+  +-------------------------+--------------------------------------------------------------+---------------------------------------------------------------+---------------------------------------------------------------+
+  | 0x5b’000101             | To get the information of ESP32’s Wi-Fi mode and its status. |                                                               | No data field is contained.                                   |
+  |                         |                                                              |                                                               | When receiving this control frame, ESP32 will send back       |
+  |                         |                                                              |                                                               | a follow-up  frame of Wi-Fi connection state report to        |
+  |                         |                                                              |                                                               | the mobile phone with the information of the current opmode,  |
+  |                         |                                                              |                                                               | connection status, SSID and so on.                            |
+  |                         |                                                              |                                                               | The types of information sent to the mobile phone is          |
+  |                         |                                                              |                                                               | defined by the application installed on the phone.            |
+  +-------------------------+--------------------------------------------------------------+---------------------------------------------------------------+---------------------------------------------------------------+
+  | 0x6b’000110             | Disconnect the STA device from the SoftAP (in SoftAP mode).  |                                                               | Date[0~5] is taken as the MAC address for the STA device.     |
+  |                         |                                                              |                                                               | If there is a second STA device, then it uses data[6-11]      |
+  |                         |                                                              |                                                               | and the rest can be done in the same manner.                  |
+  +-------------------------+--------------------------------------------------------------+---------------------------------------------------------------+---------------------------------------------------------------+
+  | 0x7b'000111             | Get the version information.                                 |                                                               |                                                               |
+  +-------------------------+--------------------------------------------------------------+---------------------------------------------------------------+---------------------------------------------------------------+
+  | 0x8b’001000             | Disconnect the BLE GATT link.                                |                                                               | ESP32 will disconnect the BLE GATT link                       |
+  |                         |                                                              |                                                               | after receives this command.                                  |
+  +-------------------------+--------------------------------------------------------------+---------------------------------------------------------------+---------------------------------------------------------------+
+  | 0x9b’001001             | Get the Wi-Fi list.                                          | To get ESP32 to scan the Wi-Fi access points around.          | No data field is contained.                                   |
+  |                         |                                                              |                                                               | When receiving this control frame,                            |
+  |                         |                                                              |                                                               | ESP32 will send back a follow-up frame of Wi-Fi list          |
+  |                         |                                                              |                                                               | report to the mobile phone.                                   |
+  +-------------------------+--------------------------------------------------------------+---------------------------------------------------------------+---------------------------------------------------------------+
+
+ **1.2 Data Frame (0x1b’01)**
+
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | Data Frame   | Implication                                        | Explanation                                                   | Note                                                                  |
+  +==============+====================================================+===============================================================+=======================================================================+
+  | 0x0b’000000  | Send the negotiation data.                         | The negotiation data will be sent to the callback             | The length of the data depends on the length field.                   |
+  |              |                                                    | function registered in the application layer.                 |                                                                       |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0x1b’000001  | Send the BSSID for STA mode.                       | To send the BSSID of the AP for the STA device to             | The length of the data depends on the length field.                   |
+  |              |                                                    | connect under the condition that  the SSID is hidden.         | When the transmission direction is ESP32 to the mobile phone,         |
+  |              |                                                    |                                                               | it means to provide the mobile phone with the needed information.     |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0x2b’000010  | Send the SSID for STA mode.                        | To send the SSID of the AP for the STA device to connect.     | The length of the data depends on the length field.                   |
+  |              |                                                    |                                                               | When the transmission direction is ESP32 to the mobile phone,         |
+  |              |                                                    |                                                               | it means to provide the mobile phone with the needed information.     |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0x3b’000011  | Send the password for STA mode.                    | To send the password of the AP for the STA device to connect. | The length of the data depends on the length field.                   |
+  |              |                                                    |                                                               | When the transmission direction is ESP32 to the mobile phone,         |
+  |              |                                                    |                                                               | it means to provide the mobile phone with the needed information.     |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0x4b’000100  | Send the SSID for SoftAP mode.                     |                                                               | The length of the data depends on the length field.                   |
+  |              |                                                    |                                                               | When the transmission direction is ESP32 to the mobile phone,         |
+  |              |                                                    |                                                               | it means to provide the mobile phone with the needed information.     |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0x5b’000101  | Send the password for SoftAPmode.                  |                                                               | The length of the data depends on the length field.                   |
+  |              |                                                    |                                                               | When the transmission direction is ESP32 to the mobile phone,         |
+  |              |                                                    |                                                               | it means to provide the mobile phone with the needed information.     |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0x6b’000110  | Set the maximum connection number for SoftAP mode. |                                                               | data[0] represents the value of the connection number,                |
+  |              |                                                    |                                                               | ranging from 1 to 4. When the transmission direction is ESP32         |
+  |              |                                                    |                                                               | to the mobile phone, it means to provide the mobile phone with        |
+  |              |                                                    |                                                               | the needed information.                                               |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0x7b’000111  | Set the authentication mode for the SoftAP.        |                                                               | data[0]:                                                             |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | 0x00: OPEN                                                            |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | 0x01: WEP                                                             |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | 0x02: WPA_PSK                                                         |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | 0x03: WPA2_PSK                                                        |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | 0x04: WPA_WPA2_PSK                                                    |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | When the transmission direction is ESP32 to the mobile phone,         |
+  |              |                                                    |                                                               | it means to provide the mobile phone with the needed information.     |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0x8b’001000  | Set the channel amount for SoftAP mode.            |                                                               | data[0] represents the quantity of the supported channels,            |
+  |              |                                                    |                                                               | ranging from 1 to 14.                                                 |
+  |              |                                                    |                                                               | When the transmission direction is ESP32 to the mobile phone,         |
+  |              |                                                    |                                                               | it means to provide the mobile phone with the needed information.     |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0x9b’001001  | Username                                           | It provides the username of the GATT client when using        | The length of the data depends on the length field.                   |
+  |              |                                                    | encryption of enterprise level.                               |                                                                       |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0xab’001010  | CA Certification                                   | It provides the CA Certification when using encryption        | The length of the data depends on the length field.                   |
+  |              |                                                    | of enterprise level.                                          | The frame supports to be fragmented if the data length is not enough. |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0xbb’001011  | Client Certification                               | It provides the client certification when                     | The length of the data depends on the length field.                   |
+  |              |                                                    | using encryption of enterprise level.                         | The frame supports to be fragmented if the data length is not enough. |
+  |              |                                                    | Whether the private key is contained or not                   |                                                                       |
+  |              |                                                    | depends on the content of the certification.                  |                                                                       |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0xcb’001100  | Server Certification                               | It provides the sever certification when using                | The length of the data depends on the length field.                   |
+  |              |                                                    | encryption of enterprise level. Whether the private key is    | The frame supports to be fragmented if the data length is not enough. |
+  |              |                                                    | contained or not depends on the content of the certification. |                                                                       |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0xdb’001101  | ClientPrivate Key                                  | It provides the private key of the client when                | The length of the data depends on the length field.                   |
+  |              |                                                    | using encryption of enterprise level.                         | The frame supports to be fragmented if the data length is not enough. |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0xeb’001110  | ServerPrivate Key                                  | It provides the private key of the sever when                 | The length of the data depends on the length field.                   |
+  |              |                                                    | using encryption of enterprise level.                         | The frame supports to be fragmented if the data length is not enough. |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0xfb’001111  | Wi-Fi Connection State Report                      | To notify the phone of the ESP32's Wi-Fi status,              | data[0] represents opmode, including:                                 |
+  +              +                                                    + including STA status and SoftAP status.                       +-----------------------------------------------------------------------+
+  |              |                                                    | It is for the STA device to connect to the                    | 0x00: NULL                                                            |
+  +              +                                                    + mobile phone or the SoftAP.                                   +-----------------------------------------------------------------------+
+  |              |                                                    | However, when the mobile phone receives the Wi-Fi status,     | 0x01: STA                                                             |
+  +              +                                                    + it can reply to other frames in addition to this frame.       +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | 0x02: SoftAP                                                          |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | 0x03: SoftAP&STA                                                      |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | data[1]:the connection state of the STA device,                      |
+  |              |                                                    |                                                               | 0x0 indicates a connection state,                                     |
+  |              |                                                    |                                                               | and others represent a disconnected state;                            |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | data[2]:the connection state of the SoftAP,                          |
+  |              |                                                    |                                                               | that is, how many STA devices have been connected.                    |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | data[3] and the subsequent is in accordance with the                  |
+  |              |                                                    |                                                               | format of SSID/BSSID information.                                     |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0x10b’010000 | Version                                            |                                                               | data[0]= great versiondata[1]= sub version                            |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0x11B’010001 | Wi-Fi List                                         | To send the Wi-Fi list to ESP32.                              | The format of the data frame is length + RSSI + SSID                  |
+  |              |                                                    |                                                               | and it supports to be sent into fragments                             |
+  |              |                                                    |                                                               | if the data length is too long.                                       |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0x12B’010010 | Report Error                                       | To notify the mobile phone that there is an error with BluFi. | 0x00: sequence error                                                  |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | 0x01: checksum error                                                  |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | 0x02: decrypt error                                                   |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | 0x03: encrypt error                                                   |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | 0x04: init security error                                             |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | 0x05: dh malloc error                                                 |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | 0x06: dh param error                                                  |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | 0x07: read param  error                                               |
+  +              +                                                    +                                                               +-----------------------------------------------------------------------+
+  |              |                                                    |                                                               | 0x08: make public error                                               |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+  | 0x13B’010011 | Custom Data                                        | To send or receive custom data.                               | The data frame supports to be sent into                               |
+  |              |                                                    |                                                               | fragments if the data length is too long.                             |
+  +--------------+----------------------------------------------------+---------------------------------------------------------------+-----------------------------------------------------------------------+
+
+2. Frame Control
+
+   Control field, takes 1 byte and each bit has a different meaning.
+
+   +--------------------+------------------------------------------------------------------------------------------------+
+   | Bit                | Meaning                                                                                        |
+   +====================+================================================================================================+
+   | 0x01               | Indicates whether the frame is encrypted.                                                      |
+   +                    +------------------------------------------------------------------------------------------------+
+   |                    | 1 means encryption, and 0 means unencrypted.                                                   |
+   +                    +------------------------------------------------------------------------------------------------+
+   |                    | The encrypted part of the frame includes                                                       |
+   |                    | the full clear data before the DATA field is encrypted (no checksum).                          |
+   +                    +------------------------------------------------------------------------------------------------+
+   |                    | Control frame is not encrypted, so this bit is 0.                                              |
+   +--------------------+------------------------------------------------------------------------------------------------+
+   | 0x02               | The data field that indicates whether a frame contains                                         |
+   |                    | a checksum (such as SHA1,MD5,CRC, etc.) for the end of                                         |
+   |                    | the frame data field includes SEQUCNE + data length + clear text.                              |
+   |                    | Both the control frame and the data frame can contain a check bit or not.                      |
+   +--------------------+------------------------------------------------------------------------------------------------+
+   | 0x04               | Represents the data direction.                                                                 |
+   +--------------------+------------------------------------------------------------------------------------------------+
+   |                    | 0 means the mobile phone to ESP32;                                                             |
+   +--------------------+------------------------------------------------------------------------------------------------+
+   |                    | 1 means ESP32 to the mobile phone.                                                             |
+   +--------------------+------------------------------------------------------------------------------------------------+
+   | 0x08               | Indicates whether the other person is required to reply to an ACK.                             |
+   +--------------------+------------------------------------------------------------------------------------------------+
+   |                    | 0 indicates no requirement;                                                                    |
+   +--------------------+------------------------------------------------------------------------------------------------+
+   |                    | 1 indicates to reply Ack.                                                                      |
+   +--------------------+------------------------------------------------------------------------------------------------+
+   | 0x10               | Indicates whether there are subsequent data fragments.                                         |
+   +--------------------+------------------------------------------------------------------------------------------------+
+   |                    | 0 indicates that there are no subsequent data fragments for this frame;                        |
+   +--------------------+------------------------------------------------------------------------------------------------+
+   |                    | 1 indicates that there are subsequent data fragments and used to transmit longer data.         |
+   +--------------------+------------------------------------------------------------------------------------------------+
+   |                    | In the case of a frag frame,                                                                   |
+   |                    | the total length of the current content section + subsequent content section is given,         |
+   |                    | in the first 2 bytes of the data field (that is, the content data of the maximum support 64K). |
+   +--------------------+------------------------------------------------------------------------------------------------+
+   | 0x10~0x80 reserved |                                                                                                |
+   +--------------------+------------------------------------------------------------------------------------------------+
+
+3. Sequence Control
+
+   Sequence control field. When a frame is sent,the value of sequence fied is automatically incremented by 1 regardless of the type of frame, which prevents Replay Attack. The sequence is cleared after each reconnection.
+
+4. Length
+
+   The length of the data field that does not include CheckSum.
+
+5. Data
+
+   The instruction of the data field is different according to various values of Type or Subtype. Please refer to the table above.
+
+6. CheckSum
+
+   This field takes 2 bytes that is used to check "sequence + data length + clear text data".
+
+The Security Implementation of ESP32
+-------------------------------------
+
+1. Securing data
+
+   To ensure that the transmission of the Wi-Fi SSID and password is secure, the message needs to be encrypted using symmetric encryption algorithms, such as AES, DES and so on. Before using symmetric encryption algorithms, the devices are required to negotiate (or generate) a shared key using an asymmetric encryption algorithm (DH, RSA, ECC, etc).
+
+2. Ensuring data integrity
+
+   To ensure data integrity, you need to add a checksum algorithm, such as SHA1, MD5, CRC, etc.
+
+3. Securing identity (signature)
+
+   Algorithm like RSA can be used to secure identity. But for DH, it needs other algorithms as an companion for signature.
+
+4. Replay attack prevention
+
+   It is added to the Sequence field and used during the checksum verification.
+
+   For the coding of ESP32, you can determine and develop the security processing, such as key negotiation. The mobile application sends the negotiation data to ESP32 and then the data will be sent to the application layer for processing. If the application layer does not process it, you can use the DH encryption algorithm provided by BluFi to negotiate the key.
+  
+   The application layer needs to register several security-related functions to BluFi:
+
+.. code-block:: c 
+
+   typedef void (*esp_blufi_negotiate_data_handler_t)(uint8_t *data, int len, uint8_t **output_data, int *output_len, bool *need_free)
+
+This function is for ESP32 to receive normal data during negotiation, and after processing is completed, the data will be transmitted using Output_data and Output_len.
+
+BluFi will send output_data from Negotiate_data_handler after Negotiate_data_handler is called.
+
+Here are two "*", because the length of the data to be emitted is unknown that requires the function to allocate itself (malloc) or point to the global variable, and to inform whether the memory needs to be freed by NEED_FREE.
+
+.. code-block:: c
+
+   typedef int (* esp_blufi_encrypt_func_t)(uint8_t iv8, uint8_t *crypt_data, int cyprt_len) 
+
+The data to be encrypted and decrypted must use the same length. The IV8 is a 8 bit sequence value of frames, which can be used as a 8 bit of IV.
+
+.. code-block:: c
+
+   typedef int (* esp_blufi_decrypt_func_t)(uint8_t iv8, uint8_t *crypt_data, int crypt_len)
+
+The data to be encrypted and decrypted must use the same length. The IV8 is a 8 bit sequence value of frames, which can be used as a 8 bit of IV.
+
+.. code-block:: c
+
+   typedef uint16_t (*esp_blufi_checksum_func_t)(uint8_t iv8, uint8_t *data, int len)
+
+This function is used to compute CheckSum and return a value of CheckSum. BluFi uses the returned value to compare the CheckSum of the frame.
+
+GATT Related Instructions
+-------------------------
+
+UUID
+>>>>>
+
+BluFi Service UUID: 0xFFFF,16 bit
+
+BluFi (the mobile -> ESP32): 0xFF01, writable
+
+Blufi (ESP32 -> the mobile phone): 0xFF02, readable and callable
+
+.. note::
+
+       1. The Ack mechanism is already defined in the profile, but there is no implementation based on the code for the time being.
+
+       2. Other parts have been implemented.
\ No newline at end of file
index 3e8b2ece5186657dcb75a6f0ec013fca6ca6ec4a..3f1fafc252f41bace7c61c8675e165e55cdb9849 100644 (file)
@@ -23,4 +23,5 @@ API Guides
    ROM debug console <romconsole>
    WiFi Driver <wifi>
    Mesh Stack <mesh>
+   BluFi <blufi>
    External SPI-connected RAM <external-ram>
index 859cf4f650e0705d0fb3057e3b68f71f1b8a1d70..1c1f326cf397aaaaf45d3352b364d67facc2fccb 100644 (file)
@@ -73,25 +73,49 @@ as the default error-handling code in the application development phase. However
 
 ESP32 Wi-Fi Programming Model
 ------------------------------
-The ESP32 Wi-Fi programming model is depicted as follows::
-
-                            default handler              user handler
-   -----------               -------------               -------------
-  |           |   event     |             | callback or |             |
-  |   TCPIP   | --------->  |    event    | ----------> | application |
-  |   stack   |             |     task    |  event      |    task     |
-   -----------               -------------               -------------
-                                  /|\                          |
-                                   |                           |
-                            event  |                           |
-                                   |                           |
-                                   |                           |
-                              -------------                    |
-                             |             |                   |
-                             | Wi-Fi Driver|/__________________|
-                             |             |\     API call
-                             |             |
-                              -------------
+The ESP32 Wi-Fi programming model is depicted as follows:
+
+.. blockdiag::
+    :caption: Wi-Fi Programming Model
+    :align: center
+
+    blockdiag wifi-programming-model {
+
+        # global attributes
+        node_height = 60;
+        node_width = 100;
+        span_width = 100;
+        span_height = 60;
+        default_shape = roundedbox;
+        default_group_color = none;
+
+        # node labels
+        TCP_STACK [label="TCP\n stack", fontsize=12];
+        EVNT_TASK [label="Event\n task", fontsize=12];
+        APPL_TASK [label="Application\n task", width = 120, fontsize=12];
+        WIFI_DRV  [label="Wi-Fi\n Driver", width = 120, fontsize=12];
+        KNOT [shape=none];
+
+        # node connections + labels
+        TCP_STACK -> EVNT_TASK [label=event];
+        EVNT_TASK -> APPL_TASK [label="callback\n or event"];
+
+        # arrange nodes vertically
+        group {
+           label = "default handler";
+           orientation = portrait;
+           EVNT_TASK <- WIFI_DRV [label=event];
+        }
+
+        # intermediate node
+        group {
+            label = "user handler";
+            orientation = portrait;
+            APPL_TASK -- KNOT;
+        }
+        WIFI_DRV <- KNOT [label="API\n call"];
+    }
+
 
 The Wi-Fi driver can be considered a black box that knows nothing about high-layer code, such as the
 TCPIP stack, application task, event task, etc. All the Wi-Fi driver can do is receive API calls from the high layer,
@@ -211,78 +235,61 @@ Currently, the ESP32 implementation will never generate this event. It may be re
 
 ESP32 Wi-Fi Station General Scenario
 ---------------------------------------
-Below is a "big scenario" which describes some small scenarios in Station mode::
-
-    ---------           ---------           ---------           ---------          ---------
-   |  Main   |         |   app   |         |  Event  |         |  LwIP   |        |  Wi-Fi  |
-   |  task   |         |   task  |         |   task  |         |  task   |        |  task   |
-    ---------           ---------           ---------           ---------          ---------
-        |                   |                   |                   |                  |         ---
-        |              1.1> create/init LwIP    |                   |                  |          |
-        |---------------------------------------------------------->|                  |          |
-        |     1.2> create/init event            |                   |                  |       
-        |-------------------------------------->|                   |                  |      1. Init Phase
-        |                   |    1.3> create/init Wi-Fi             |                  |        
-        |----------------------------------------------------------------------------->|          |
-        |  1.4> create app task                 |                   |                  |          |
-        |------------------>|                   |                   |                  |          |
-        |                   |                   |                   |                  |         ---
-        |                   |                   |                   |                  |          |
-        |                   |                   |                   |                  |         
-        |                   |    2> configure Wi-Fi                 |                  |      2. Configure Phase
-        |----------------------------------------------------------------------------->|         
-        |                   |                   |                   |                  |          |
-        |                   |                   |                   |                  |         ---
-        |                   |         3.1> start Wi-Fi              |                  |          |
-        |----------------------------------------------------------------------------->|     
-        |                   |                   |     3.2 > SYSTEM_EVENT_STA_START     |     3. Start Phase
-        |                   |                   |<-------------------------------------|          
-        |              3.3> SYSTEM_EVENT_STA_START                  |                  |          |
-        |                   |<------------------|                   |                  |         ---
-        |                   |                   |                   |                  |          |
-        |                   |                   |                   |                  |          |
-        |                   |               4.1> connect wifi       |                  |          |
-        |                   |--------------------------------------------------------->|     4. Connect Phase
-        |                   |                   |   4.2> SYSTEM_EVENT_STA_CONNECTED    |          |
-        |                   |                   |<-------------------------------------|          |
-        |              4.3> SYSTEM_EVENT_STA_CONNECTED              |                  |          |
-        |                   |<------------------|                   |                  |         ---
-        |                   |                   |                   |                  |          |
-        |                   |                   |                   |                  |          |
-        |                   |               5.1> start DHCP client  |                  |          |
-        |                   |                   |------------------>|                  |          |
-        |                   |               5.2> SYSTEM_EVENT_STA_GOT_IP               |          |
-        |                   |                   |<------------------|                  |          
-        |                 5.3> SYSTEM_EVENT_STA_GOT_IP              |                  |     5. Got IP Phase
-        |                   |<------------------|                   |                  |          
-        |                   |-----              |                   |                  |          |
-        |                   |     | 5.4> socket related init        |                  |          |
-        |                   |<----              |                   |                  |          |
-        |                   |                   |                   |                  |         ---
-        |                   |                   |   6.1> SYSTEM_EVENT_STA_DISCONNECTED |          |
-        |                   |                   |<-------------------------------------|     
-        |              6.2> SYSTEM_EVENT_STA_DISCONNECTED           |                  |     6. Disconnect Phase     
-        |                   |<------------------|                   |                  |     
-        |                   |-----              |                   |                  |          |
-        |                   |     | 6.3> disconnect handling        |                  |          |
-        |                   |<----              |                   |                  |         ---
-        |                   |                   |                   |                  |          |
-        |                   |               7.1> SYSTEM_EVENT_STA_GOT_IP               |          |
-        |                   |                   |<------------------|                  |          |
-        |                 7.2> SYSTEM_EVENT_STA_GOT_IP              |                  |          
-        |                   |<------------------|                   |                  |    7. IP change phase
-        |                   |-----              |                   |                  |          
-        |                   |     | 7.3> socket error handling      |                  |          |
-        |                   |<----              |                   |                  |          |
-        |                   |                   |                   |                  |         ---
-        |                   |           8.1> disconnect Wi-Fi       |                  |          |
-        |                   |--------------------------------------------------------->|          
-        |                   |           8.2> stop Wi-Fi             |                  |    8. Deinit phase      
-        |                   |--------------------------------------------------------->|          
-        |                   |           8.3> deinit Wi-Fi           |                  |          |
-        |                   |--------------------------------------------------------->|          |
-        |                   |                   |                   |                  |         ---  
-  
+Below is a "big scenario" which describes some small scenarios in Station mode:
+
+.. seqdiag::
+    :caption: Sample Wi-Fi Event Scenarios in Station Mode
+    :align: center
+
+    seqdiag sample-scenarios-station-mode {
+        activation = none;
+        node_width = 80;
+        node_height = 60;
+        edge_length = 140;
+        span_height = 5;
+        default_shape = roundedbox;
+        default_fontsize = 12; 
+
+        MAIN_TASK  [label = "Main\ntask"]; 
+        APP_TASK   [label = "App\ntask"];
+        EVENT_TASK [label = "Event\ntask"];
+        LWIP_TASK  [label = "LwIP\ntask"];
+        WIFI_TASK  [label = "Wi-Fi\ntask"];
+
+        === 1. Init Phase ===
+        MAIN_TASK  ->  LWIP_TASK   [label="1.1> Create / init LwIP"];
+        MAIN_TASK  ->  EVENT_TASK  [label="1.2> Create / init event"];
+        MAIN_TASK  ->  WIFI_TASK   [label="1.3> Create / init Wi-Fi"];
+        MAIN_TASK  ->  APP_TASK    [label="1.4> Create app task"];
+        === 2. Configure Phase ===
+        MAIN_TASK  ->  WIFI_TASK   [label="2> Configure Wi-Fi"];
+        === 3. Start Phase ===
+        MAIN_TASK  ->  WIFI_TASK   [label="3.1> Start Wi-Fi"];
+        EVENT_TASK <-  WIFI_TASK   [label="3.2> SYSTEM_EVENT_STA_START"];
+        APP_TASK   <-  EVENT_TASK  [label="3.3> SYSTEM_EVENT_STA_START"];
+        === 4. Connect Phase ===
+        APP_TASK   ->  WIFI_TASK   [label="4.1> Connect Wi-Fi"];
+        EVENT_TASK <-  WIFI_TASK   [label="4.2> SYSTEM_EVENT_STA_CONNECTED"];
+        APP_TASK   <- EVENT_TASK   [label="4.3> SYSTEM_EVENT_STA_CONNECTED"];
+        === 5. Got IP Phase ===
+        EVENT_TASK ->  LWIP_TASK   [label="5.1> Start DHCP client"];
+        EVENT_TASK <-  LWIP_TASK   [label="5.2> SYSTEM_EVENT_STA_GOT_IP"];
+        APP_TASK   <-  EVENT_TASK  [label="5.3> SYSTEM_EVENT_STA_GOT_IP"];
+        APP_TASK   ->  APP_TASK    [label="5.4> socket related init"];
+        === 6. Disconnect Phase ===
+        EVENT_TASK <-  WIFI_TASK   [label="6.1> SYSTEM_EVENT_STA_DISCONNECTED"];
+        APP_TASK   <-  EVENT_TASK  [label="6.2> SYSTEM_EVENT_STA_DISCONNECTED"];
+        APP_TASK   ->  APP_TASK    [label="6.3> disconnect handling"];
+        === 7. IP Change Phase ===
+        EVENT_TASK <-  LWIP_TASK   [label="7.1> SYSTEM_EVENT_STA_GOT_IP"];
+        APP_TASK   <-  EVENT_TASK  [label="7.2> SYSTEM_EVENT_STA_GOT_IP"];
+        APP_TASK   ->  APP_TASK    [label="7.3> Socket error handling"];
+        === 8. Deinit Phase ===
+        APP_TASK   ->  WIFI_TASK   [label="8.1> Disconnect Wi-Fi"];
+        APP_TASK   ->  WIFI_TASK   [label="8.2> Stop Wi-Fi"];
+        APP_TASK   ->  WIFI_TASK   [label="8.3> Deinit Wi-Fi"];
+    }
+
 
 1. Wi-Fi/LwIP Init Phase
 ++++++++++++++++++++++++++++++
@@ -349,63 +356,51 @@ In step 4.2, the Wi-Fi connection may fail because, for example, the password is
 
 ESP32 Wi-Fi soft-AP General Scenario
 ---------------------------------------------
-Below is a "big scenario" which describes some small scenarios in Soft-AP mode::
-
-    ---------           ---------           ---------           ---------          ---------
-   |  Main   |         |   app   |         |  Event  |         |  LwIP   |        |  Wi-Fi  |
-   |  task   |         |   task  |         |   task  |         |  task   |        |  task   |
-    ---------           ---------           ---------           ---------          ---------
-        |                   |                   |                   |                  |
-        |                   |                   |                   |                  |         ---
-        |              1.1> create/init LwIP    |                   |                  |          |
-        |---------------------------------------------------------->|                  |          |
-        |     1.2> create/init event            |                   |                  |          
-        |-------------------------------------->|                   |                  |     1. Init Phase
-        |                   |    1.3> create/init Wi-Fi             |                  |          
-        |----------------------------------------------------------------------------->|          |
-        |  1.4> create app task                 |                   |                  |          |
-        |------------------>|                   |                   |                  |          |
-        |                   |                   |                   |                  |         ---
-        |                   |                   |                   |                  |          |
-        |                   |                   |                   |                  |          
-        |                   |    2> configure Wi-Fi                 |                  |     2. Configure Phase
-        |----------------------------------------------------------------------------->|          
-        |                   |                   |                   |                  |          |
-        |                   |                   |                   |                  |         ---
-        |                   |                   |                   |                  |          |
-        |                   |         3.1> start Wi-Fi              |                  |          
-        |----------------------------------------------------------------------------->|     3. Start Phase
-        |                   |                   |     3.2 > SYSTEM_EVENT_AP_START      |          
-        |                   |                   |<-------------------------------------|          |
-        |              3.3> SYSTEM_EVENT_AP_START                   |                  |          |
-        |                   |<------------------|                   |                  |         ---
-        |                   |                   |                   |                  |          |
-        |                   |                   |                   |                  |          
-        |                   |                   |   4.1> SYSTEM_EVENT_AP_STACONNECTED  |     4. Connect Phase      
-        |                   |                   |<-------------------------------------|          
-        |              4.2> SYSTEM_EVENT_AP_STACONNECTED            |                  |          |
-        |                   |<------------------|                   |                  |         ---
-        |                   |                   |                   |                  |          |
-        |                   |                   |                   |                  |          |
-        |                   |                   |   5.1> SYSTEM_EVENT_STA_DISCONNECTED |          
-        |                   |                   |<-------------------------------------|     5. Disconnect Phase
-        |              5.2> SYSTEM_EVENT_STA_DISCONNECTED           |                  |          
-        |                   |<------------------|                   |                  |          |
-        |                   |-----              |                   |                  |          |
-        |                   |     | 5.3> disconnect handling        |                  |          |
-        |                   |<----              |                   |                  |         ---
-        |                   |                   |                   |                  |          |
-        |                   |                   |                   |                  |          |
-        |                   |                   |                   |                  |          |
-        |                   |           6.1> disconnect Wi-Fi       |                  |          |
-        |                   |--------------------------------------------------------->|          
-        |                   |           6.2> stop Wi-Fi             |                  |    6. Deinit phase      
-        |                   |--------------------------------------------------------->|          
-        |                   |           6.3> deinit Wi-Fi           |                  |          |
-        |                   |--------------------------------------------------------->|          |
-        |                   |                   |                   |                  |         ---  
-        |                   |                   |                   |                  |         
-  
+Below is a "big scenario" which describes some small scenarios in Soft-AP mode:
+
+ .. seqdiag::
+    :caption: Sample Wi-Fi Event Scenarios in Soft-AP Mode
+    :align: center
+
+    seqdiag sample-scenarios-soft-ap-mode {
+        activation = none;
+        node_width = 80;
+        node_height = 60;
+        edge_length = 140;
+        span_height = 5;
+        default_shape = roundedbox;
+        default_fontsize = 12; 
+
+        MAIN_TASK  [label = "Main\ntask"]; 
+        APP_TASK   [label = "App\ntask"];
+        EVENT_TASK [label = "Event\ntask"];
+        LWIP_TASK  [label = "LwIP\ntask"];
+        WIFI_TASK  [label = "Wi-Fi\ntask"];
+
+        === 1. Init Phase ===
+        MAIN_TASK  ->  LWIP_TASK   [label="1.1> Create / init LwIP"];
+        MAIN_TASK  ->  EVENT_TASK  [label="1.2> Create / init event"];
+        MAIN_TASK  ->  WIFI_TASK   [label="1.3> Create / init Wi-Fi"];
+        MAIN_TASK  ->  APP_TASK    [label="1.4> Create app task"];
+        === 2. Configure Phase ===
+        MAIN_TASK  ->  WIFI_TASK   [label="2> Configure Wi-Fi"];
+        === 3. Start Phase ===
+        MAIN_TASK  ->  WIFI_TASK   [label="3.1> Start Wi-Fi"];
+        EVENT_TASK <-  WIFI_TASK   [label="3.2> SYSTEM_EVENT_AP_START"];
+        APP_TASK   <-  EVENT_TASK  [label="3.3> SYSTEM_EVENT_AP_START"];
+        === 4. Connect Phase ===
+        EVENT_TASK <-  WIFI_TASK   [label="4.1> SYSTEM_EVENT_AP_STA_CONNECTED"];
+        APP_TASK   <- EVENT_TASK   [label="4.2> SYSTEM_EVENT_AP_STA_CONNECTED"];
+        === 5. Disconnect Phase ===
+        EVENT_TASK <-  WIFI_TASK   [label="5.1> SYSTEM_EVENT_STA_DISCONNECTED"];
+        APP_TASK   <-  EVENT_TASK  [label="5.2> SYSTEM_EVENT_STA_DISCONNECTED"];
+        APP_TASK   ->  APP_TASK    [label="5.3> disconnect handling"];
+        === 6. Deinit Phase ===
+        APP_TASK   ->  WIFI_TASK   [label="6.1> Disconnect Wi-Fi"];
+        APP_TASK   ->  WIFI_TASK   [label="6.2> Stop Wi-Fi"];
+        APP_TASK   ->  WIFI_TASK   [label="6.3> Deinit Wi-Fi"];
+    }
+
 
 ESP32 Wi-Fi Scan
 ------------------------
@@ -514,38 +509,34 @@ The scan type and other scan attributes are configured by esp_wifi_scan_start. T
 Scan All APs In All Channels(foreground)
 +++++++++++++++++++++++++++++++++++++++++++
 
-Scenario::
-
-    ---------           ---------           --------- 
-   |  app    |         |  event  |         |   Wi-Fi |
-   |  task   |         |   task  |         |   task  |
-    ---------           ---------           --------- 
-        |                   |                   |
-        |                   |                   |
-        |      1.1> Configure country code      |
-        |-------------------------------------->|
-        |      1.2> Scan configuration          |
-        |-------------------------------------->|
-        |                   |                   |
-        |                   |                   |
-        |                   |                   |----
-        |                   |                   |    | 2.1> Scan channel 1
-        |                   |                   |<---
-        |                   |                   |----
-        |                   |                   |    | 2.2> Scan channel 2
-        |                   |                   |<---
-        |                   |                   |
-        |                   |                   |      ....  ...
-        |                   |                   |
-        |                   |                   |----
-        |                   |                   |    | 2.x> Scan channel N
-        |                   |                   |<---
-        |                   |                   |
-        |           3.1 SYSTEM_EVENT_SCAN_DONE  |
-        |                   |<------------------|
-        |  3.2 SYSTEM_EVENT_SCAN_DONE           |
-        |<------------------|                   |
-        |                   |                   |
+Scenario:
+
+.. seqdiag::
+    :caption: Foreground Scan of all Wi-Fi Channels
+    :align: center
+
+    seqdiag foreground-scan-all-channels {
+        activation = none;
+        node_width = 80;
+        node_height = 60;
+        edge_length = 160;
+        span_height = 5;
+        default_shape = roundedbox;
+        default_fontsize = 12; 
+
+        APP_TASK   [label = "App\ntask"];
+        EVENT_TASK [label = "Event\ntask"];
+        WIFI_TASK  [label = "Wi-Fi\ntask"];
+
+        APP_TASK   ->  WIFI_TASK  [label="1.1 > Configure country code"];
+        APP_TASK   ->  WIFI_TASK  [label="1.2 > Scan configuration"];
+        WIFI_TASK  ->  WIFI_TASK  [label="2.1 > Scan channel 1"];
+        WIFI_TASK  ->  WIFI_TASK  [label="2.2 > Scan channel 2"];
+        WIFI_TASK  ->  WIFI_TASK  [label="..."];
+        WIFI_TASK  ->  WIFI_TASK  [label="2.x > Scan channel N"];
+        EVENT_TASK <-  WIFI_TASK  [label="3.1 > SYSTEM_EVENT_SCAN_DONE"];
+        APP_TASK   <-  EVENT_TASK [label="3.2 > SYSTEM_EVENT_SCAN_DONE"];
+    }
 
 
 The scenario above describes an all-channel, foreground scan. The foreground scan can only occur in Station mode where the station does not connect to any AP. Whether it is a foreground or background scan is totally determined by the Wi-Fi driver, and cannot be configured by the application. 
@@ -574,84 +565,70 @@ Scan-Done Event Handling Phase
 
 Scan All APs on All Channels(background)
 ++++++++++++++++++++++++++++++++++++++++
-Scenario::
-
-    ---------           ---------           --------- 
-   |  app    |         |  event  |         |   Wi-Fi |
-   |  task   |         |   task  |         |   task  |
-    ---------           ---------           --------- 
-        |                   |                   |
-        |                   |                   |
-        |      1.1> Configure country code      |
-        |-------------------------------------->|
-        |      1.2> Scan configuration          |
-        |-------------------------------------->|
-        |                   |                   |
-        |                   |                   |
-        |                   |                   |----
-        |                   |                   |    | 2.1> Scan channel 1
-        |                   |                   |<---
-        |                   |                   |----
-        |                   |                   |    | 2.2> Back to home channel H
-        |                   |                   |<---
-        |                   |                   |----
-        |                   |                   |    | 2.3> Scan channel 2
-        |                   |                   |<---
-        |                   |                   |----
-        |                   |                   |    | 2.4> Back to home channel H
-        |                   |                   |<---
-        |                   |                   |
-        |                   |                   |      ....  ...
-        |                   |                   |
-        |                   |                   |----
-        |                   |                   |    | 2.x-1> Scan channel N
-        |                   |                   |<---
-        |                   |                   |----
-        |                   |                   |    | 2.x> Back to home channel H
-        |                   |                   |<---
-        |                   |                   |
-        |           3.1 SYSTEM_EVENT_SCAN_DONE  |
-        |                   |<------------------|
-        |  3.2 SYSTEM_EVENT_SCAN_DONE           |
-        |<------------------|                   |
-        |                   |                   |
+Scenario:
+
+.. seqdiag::
+    :caption: Background Scan of all Wi-Fi Channels
+    :align: center
+
+    seqdiag background-scan-all-channels {
+        activation = none;
+        node_width = 80;
+        node_height = 60;
+        edge_length = 160;
+        span_height = 5;
+        default_shape = roundedbox;
+        default_fontsize = 12; 
+
+        APP_TASK   [label = "App\ntask"];
+        EVENT_TASK [label = "Event\ntask"];
+        WIFI_TASK  [label = "Wi-Fi\ntask"];
+
+        APP_TASK   ->  WIFI_TASK  [label="1.1 > Configure country code"];
+        APP_TASK   ->  WIFI_TASK  [label="1.2 > Scan configuration"];
+        WIFI_TASK  ->  WIFI_TASK  [label="2.1 > Scan channel 1"];
+        WIFI_TASK  ->  WIFI_TASK  [label="2.2 > Back to home channel H"];
+        WIFI_TASK  ->  WIFI_TASK  [label="2.3 > Scan channel 2"];
+        WIFI_TASK  ->  WIFI_TASK  [label="2.4 > Back to home channel H"];
+        WIFI_TASK  ->  WIFI_TASK  [label="..."];
+        WIFI_TASK  ->  WIFI_TASK  [label="2.x-1 > Scan channel N"];
+        WIFI_TASK  ->  WIFI_TASK  [label="2.x > Back to home channel H"];
+        EVENT_TASK <-  WIFI_TASK  [label="3.1 > SYSTEM_EVENT_SCAN_DONE"];
+        APP_TASK   <-  EVENT_TASK [label="3.2 > SYSTEM_EVENT_SCAN_DONE"];
+    }
 
 The scenario above is an all-channel background scan. Compared to `Scan All APs In All Channels(foreground)`_ , the difference in the all-channel background scan is that the Wi-Fi driver will scan the back-to-home channel for 30 ms before it switches to the next channel to give the Wi-Fi connection a chance to transmit/receive data.
 
 Scan for a Specific AP in All Channels
 +++++++++++++++++++++++++++++++++++++++
-Scenario::
-
-    ---------           ---------           --------- 
-   |  app    |         |  event  |         |   Wi-Fi |
-   |  task   |         |   task  |         |   task  |
-    ---------           ---------           --------- 
-        |                   |                   |
-        |                   |                   |
-        |      1.1> Configure country code      |
-        |-------------------------------------->|
-        |      1.2> Scan configuration          |
-        |-------------------------------------->|
-        |                   |                   |
-        |                   |                   |
-        |                   |                   |----
-        |                   |                   |    | 2.1> Scan channel C1
-        |                   |                   |<---
-        |                   |                   |----
-        |                   |                   |    | 2.2> Scan channel C2
-        |                   |                   |<---
-        |                   |                   |
-        |                   |                   | ...
-        |                   |                   |
-        |                   |                   |----
-        |                   |                   |    | 2.x> Scan channel CN, or the AP is found
-        |                   |                   |<---
-        |                   |                   |
-        |           3.1 SYSTEM_EVENT_SCAN_DONE  |
-        |                   |<------------------|
-        |  3.2 SYSTEM_EVENT_SCAN_DONE           |
-        |<------------------|                   |
-        |                   |                   |
+Scenario:
+
+.. seqdiag::
+    :caption: Scan of specific Wi-Fi Channels
+    :align: center
+
+    seqdiag scan-specific-channels {
+        activation = none;
+        node_width = 80;
+        node_height = 60;
+        edge_length = 160;
+        span_height = 5;
+        default_shape = roundedbox;
+        default_fontsize = 12; 
+
+        APP_TASK   [label = "App\ntask"];
+        EVENT_TASK [label = "Event\ntask"];
+        WIFI_TASK  [label = "Wi-Fi\ntask"];
+
+        APP_TASK   ->  WIFI_TASK  [label="1.1 > Configure country code"];
+        APP_TASK   ->  WIFI_TASK  [label="1.2 > Scan configuration"];
+        WIFI_TASK  ->  WIFI_TASK  [label="2.1 > Scan channel C1"];
+        WIFI_TASK  ->  WIFI_TASK  [label="2.2 > Scan channel C2"];
+        WIFI_TASK  ->  WIFI_TASK  [label="..."];
+        WIFI_TASK  ->  WIFI_TASK  [label="2.x > Scan channel CN, or the AP is found"];
+        EVENT_TASK <-  WIFI_TASK  [label="3.1 > SYSTEM_EVENT_SCAN_DONE"];
+        APP_TASK   <-  EVENT_TASK [label="3.2 > SYSTEM_EVENT_SCAN_DONE"];
+    }
 
 This scan is similar to `Scan All APs In All Channels(foreground)`_. The differences are:
 
@@ -681,60 +658,50 @@ ESP32 Wi-Fi Station Connecting Scenario
 ----------------------------------------
 Generally, the application does not need to care about the connecting process. Below is a brief introduction to the process for those who are really interested.
 
-Scenario::
-
-    ---------           ---------           --------- 
-   |  Event  |         |   Wi-Fi |         |  AP     |
-   |  task   |         |   task  |         |         |
-    ---------           ---------           --------- 
-        |                   |                   |
-        |                   |                   |       ---
-        |                   |----               |        |
-        |                   |    | 1.1> Scan    |        
-        |                   |<---               |      Scan phase
-        | 1.2> SYSTEM_EVENT_STA_DISCONNECTED    |      
-        |<------------------|                   |        |
-        |                   |                   |       ---
-        |                   |                   |        |
-        |                    2.1> Auth Request  |        |
-        |                   |------------------>|        |
-        | 2.2> SYSTEM_EVENT_STA_DISCONNECTED    |       
-        |<------------------|                   |      Auth phase
-        |                    2.3> Auth Response |       
-        |                   |<------------------|        |
-        | 2.4> SYSTEM_EVENT_STA_DISCONNECTED    |        |
-        |<------------------|                   |       ---
-        |                   |                   |        |
-        |                   | 3.1 Assoc Request |        |
-        |                   |------------------>|        |
-        | 3.2> SYSTEM_EVENT_STA_DISCONNECTED    |        
-        |<------------------|                   |     Assoc phase
-        |                    3.3 Assoc Response |       
-        |                   |<------------------|        |
-        | 3.4> SYSTEM_EVENT_STA_DISCONNECTED    |        |
-        |<------------------|                   |        |
-        |                   |                   |       ---  
-        |                   |                   |        |
-        |                   | 4.1> 1/4 EAPOL    |        |
-        |                   |<------------------|        |
-        | 4.2> SYSTEM_EVENT_STA_DISCONNECTED    |        |
-        |<------------------|                   |        |
-        |                   | 4.3> 2/4 EAPOL    |        |
-        |                   |------------------>|        |
-        | 4.4> SYSTEM_EVENT_STA_DISCONNECTED    |        
-        |<------------------|                   |     4-way handshake phase
-        |                   | 4.5> 3/4 EAPOL    |        
-        |                   |<------------------|        |
-        | 4.6> SYSTEM_EVENT_STA_DISCONNECTED    |        |
-        |<------------------|                   |        |
-        |                   | 4.7> 4/4 EAPOL    |        |
-        |                   |------------------>|        |
-        | 4.8> SYSTEM_EVENT_STA_DISCONNECTED    |        |
-        |<------------------|                   |        |
-        |                   |                   |        |
-        | 4.9> SYSTEM_EVENT_STA_DISCONNECTED    |        |
-        |<------------------|                   |       ---  
-        |                   |                   | 
+Scenario:
+
+.. seqdiag::
+    :caption: Wi-Fi Station Connecting Process
+    :align: center
+
+    seqdiag station-connecting-process {
+        activation = none;
+        node_width = 80;
+        node_height = 60;
+        edge_length = 160;
+        span_height = 5;
+        default_shape = roundedbox;
+        default_fontsize = 12; 
+
+        EVENT_TASK  [label = "Event\ntask"];
+        WIFI_TASK   [label = "Wi-Fi\ntask"];
+        AP          [label = "AP"];
+
+        === 1. Scan Phase ===
+        WIFI_TASK  ->  WIFI_TASK [label="1.1 > Scan"];
+        EVENT_TASK <-  WIFI_TASK [label="1.2 > SYSTEM_EVENT_STA_DISCONNECTED"];
+        === 2. Auth Phase ===
+        WIFI_TASK  ->  AP        [label="2.1 > Auth request"];
+        EVENT_TASK <-  WIFI_TASK [label="2.2 > SYSTEM_EVENT_STA_DISCONNECTED"];
+        WIFI_TASK  <-  AP        [label="2.3 > Auth response"];
+        EVENT_TASK <-  WIFI_TASK [label="2.4 > SYSTEM_EVENT_STA_DISCONNECTED"];
+        === 3. Assoc Phase ===
+        WIFI_TASK  ->  AP        [label="3.1 > Assoc request"];
+        EVENT_TASK <-  WIFI_TASK [label="3.2 > SYSTEM_EVENT_STA_DISCONNECTED"];
+        WIFI_TASK  <-  AP        [label="3.3 > Assoc response"];
+        EVENT_TASK <-  WIFI_TASK [label="3.4 > SYSTEM_EVENT_STA_DISCONNECTED"];
+        === 4. 4-way Handshake Phase ===
+        WIFI_TASK  ->  AP        [label="4.1 > 1/4 EAPOL"];
+        EVENT_TASK <-  WIFI_TASK [label="4.2 > SYSTEM_EVENT_STA_DISCONNECTED"];
+        WIFI_TASK  ->  AP        [label="4.3 > 2/4 EAPOL"];
+        EVENT_TASK <-  WIFI_TASK [label="4.4 > SYSTEM_EVENT_STA_DISCONNECTED"];
+        WIFI_TASK  ->  AP        [label="4.5 > 3/4 EAPOL"];
+        EVENT_TASK <-  WIFI_TASK [label="4.6 > SYSTEM_EVENT_STA_DISCONNECTED"];
+        WIFI_TASK  ->  AP        [label="4.7 > 4/4 EAPOL"];
+        EVENT_TASK <-  WIFI_TASK [label="4.8 > SYSTEM_EVENT_STA_DISCONNECTED"];
+        EVENT_TASK <-  WIFI_TASK [label="4.9 > SYSTEM_EVENT_STA_DISCONNECTED"];
+    }
+
 
 Scan Phase
 +++++++++++++++++++++
@@ -1598,26 +1565,73 @@ Wi-Fi Menuconfig
 Wi-Fi Buffer Configure
 +++++++++++++++++++++++
 
-If you are going to modify the default number or type of buffer, it would be helpful to also have an overview of how the buffer is allocated/freed in the data path. The following diagram shows this process in the TX direction::
+If you are going to modify the default number or type of buffer, it would be helpful to also have an overview of how the buffer is allocated/freed in the data path. The following diagram shows this process in the TX direction:
+
+.. blockdiag::
+    :caption: TX Buffer Allocation
+    :align: center
+
+    blockdiag buffer_allocation_tx {
+
+        # global attributes
+        node_height = 60;
+        node_width = 100;
+        span_width = 50;
+        span_height = 20;
+        default_shape = roundedbox;
+
+        # labels of diagram nodes
+        APPL_TASK [label="Application\n task", fontsize=12];  
+        LWIP_TASK [label="LwIP\n task", fontsize=12];  
+        WIFI_TASK [label="Wi-Fi\n task", fontsize=12];
+
+        # labels of description nodes
+        APPL_DESC [label="1> User data", width=120, height=25, shape=note, color=yellow];  
+        LWIP_DESC [label="2> Pbuf", width=120, height=25, shape=note, color=yellow];  
+        WIFI_DESC [label="3> Dynamic (Static)\n TX Buffer", width=150, height=40, shape=note, color=yellow];
+
+        # node connections
+        APPL_TASK -> LWIP_TASK -> WIFI_TASK
+        APPL_DESC -> LWIP_DESC -> WIFI_DESC [style=none]
+    }
 
-     -------------              -------------              -------------
-    | Application |            |    LwIP     |            |    Wi-Fi    |
-    |    task     | ---------> |    task     | ---------> |    task     |
-     -------------              -------------              -------------
-      1> User data               2> Pbuf                    3> Dynamic (Static) TX Buffer
 
 Description:
  - The application allocates the data which needs to be sent out.
  - The application calls TCPIP-/Socket-related APIs to send the user data. These APIs will allocate a PBUF used in LwIP, and make a copy of the user data.
  - When LwIP calls a Wi-Fi API to send the PBUF, the Wi-Fi API will allocate a "Dynamic Tx Buffer" or "Static Tx Buffer", make a copy of the LwIP PBUF, and finally send the data.
 
-The following diagram shows how buffer is allocated/freed in the RX direction::
-
-     -------------              -------------              -------------              ------------- 
-    | Application |            |    LwIP     |            |    Wi-Fi    |            |    Wi-Fi    |
-    |    Task     | <--------- |    task     | <--------- |    task     | <--------- |  Interrupt  |
-     -------------              -------------              -------------              -------------
-      4> User data               3> Pbuf                    2> Dynamic RX Buffer       1> Static RX Buffer
+The following diagram shows how buffer is allocated/freed in the RX direction:
+
+.. blockdiag::
+    :caption: RX Buffer Allocation
+    :align: center
+
+    blockdiag buffer_allocation_rx {
+
+        # global attributes
+        node_height = 60;
+        node_width = 100;
+        span_width = 40;
+        span_height = 20;
+        default_shape = roundedbox;
+
+        # labels of diagram nodes
+        APPL_TASK [label="Application\n task", fontsize=12];  
+        LWIP_TASK [label="LwIP\n task", fontsize=12];  
+        WIFI_TASK [label="Wi-Fi\n task", fontsize=12];
+        WIFI_INTR [label="Wi-Fi\n interrupt", fontsize=12];
+
+        # labels of description nodes
+        APPL_DESC [label="4> User\n Data Buffer", height=40, shape=note, color=yellow];  
+        LWIP_DESC [label="3> Pbuf", height=40, shape=note, color=yellow];  
+        WIFI_DESC [label="2> Dynamic\n RX Buffer", height=40, shape=note, color=yellow];
+        INTR_DESC [label="1> Static\n RX Buffer", height=40, shape=note, color=yellow];
+
+        # node connections
+        APPL_TASK <- LWIP_TASK <- WIFI_TASK <- WIFI_INTR
+        APPL_DESC <- LWIP_DESC <- WIFI_DESC <- INTR_DESC [style=none]
+    }
 
 Description:
 
index f44fa18bb5f0fdb82bee970ff8f979ec060710f6..584a6df252cd3b76a7b78fa3b208a01744f37d07 100644 (file)
@@ -196,7 +196,7 @@ Flash encryption keys are 32 bytes of random data. You can generate a random key
 
 Alternatively, if you're using :doc:`secure boot <secure-boot>` and have a secure boot signing key then you can generate a deterministic SHA-256 digest of the secure boot private signing key and use this as the flash encryption key::
 
-  espsecure.py digest_private-key --keyfile secure_boot_signing_key.pem my_flash_encryption_key.bin
+  espsecure.py digest_private_key --keyfile secure_boot_signing_key.pem my_flash_encryption_key.bin
 
 (The same 32 bytes is used as the secure boot digest key if you enable :ref:`reflashable mode<secure-boot-reflashable>` for secure boot.)
 
diff --git a/docs/zh_CN/api-guides/blufi.rst b/docs/zh_CN/api-guides/blufi.rst
new file mode 100644 (file)
index 0000000..1f9ec89
--- /dev/null
@@ -0,0 +1,427 @@
+BluFi
+^^^^^
+
+概览
+-----
+BluFi 是一款基于蓝牙通道的 Wi-Fi 网络配置功能,适用于 ESP32。它通过安全协议将 Wi-Fi 配置和证书传输到 ESP32,然后 ESP32 可基于这些信息连接到 AP 或建立 SoftAP。
+
+BluFi 流程的关键部分包括数据的分片、加密、校验和验证。
+
+用户可按需自定义用于对称加密、非对称加密和校验的算法。这里我们采用 DH 算法进行密钥协商、128-AES 算法用于数据加密、CRC16 算法用于校验和验证。
+
+BluFi 流程
+----------
+BluFi 配网功能包含配置 SoftAP 和 Station 两部分。
+
+下面以配置 Station 为例说明配置步骤。
+BluFi 配网的配置 Station 包含广播、连接、服务发现、协商共享密钥、传输数据、回传连接状态等步骤。
+
+ESP32 配网流程
+--------------
+
+1. ESP32 开启 GATT Server 功能,发送带有特定 *adv data* 的广播。你可以自定义该广播,该广播不属于 BluFi Profile。
+
+2. 使用手机 APP 搜索到该特定广播,手机作为 GATT Client 连接 ESP32。你可以决定使用哪款手机 APP。
+
+3. GATT 连接建立成功后,手机向 ESP32 发送“协商过程”数据帧(详情见 :ref:`frame_formats` )。
+
+4. ESP32 收到“协商过程”数据帧后,会按照使用者自定义的协商过程来解析。
+
+5. 手机与 ESP32 进行密钥协商。协商过程可使用 DH/RSA/ECC 等加密算法进行。
+
+6. 协商结束后,手机端向 ESP32 发送“设置安全模式”控制帧。
+
+7. ESP32 收到“设置安全模式”控制帧后,使用经过协商的共享密钥以及配置的安全策略对通信数据进行加密和解密。
+
+8. 手机向 ESP32 发送“BluFi 传输格式”定义的 SSID、Password 等用于 Wi-Fi 连接的必要信息。
+
+9. 手机向 ESP32 发送“Wi-Fi 连接请求”控制帧,ESP32 收到之后,识别为手机已将必要的信息传输完毕,准备连接 Wi-Fi。
+
+10. ESP32 连接到 Wi-Fi 后,发送“Wi-Fi 连接状态报告”控制帧到手机,以报告连接状态。至此配网结束。
+
+.. note::
+
+    1. 安全模式设置可在任何时候进行,ESP32 收到安全模式的配置后,会根据安全模式指定的模式进行安全相关的操作。
+
+    2. 进行对称加密和解密时,加密和解密前后的数据长度必须一致,支持原地加密和解密。
+
+配网流程图
+-----------
+
+.. seqdiag::
+    :caption: BluFi Flow Chart
+    :align: center
+
+    seqdiag blufi {
+        activation = none;
+        node_width = 80;
+        node_height = 60;
+        edge_length = 380;
+        span_height = 10;
+        default_fontsize = 12; 
+
+        Phone <- ESP32 [label="广播"];
+        Phone -> ESP32 [label="建立 GATT 链接"];
+        Phone <- ESP32 [label="协商密钥"];
+        Phone -> ESP32 [label="协商密钥"];
+        Phone -> ESP32 [label="CTRL: 设置 ESP32 手机安全模式"];
+        Phone -> ESP32 [label="DATA: SSID"];
+        Phone -> ESP32 [label="DATA: Password"];
+        Phone -> ESP32 [label="DATA: 其他信息,如 CA 认证"];
+        Phone -> ESP32 [label="CTRL: 连接到 AP"];
+        Phone <- ESP32 [label="DATA: 连接状态报告"];
+    }
+
+.. _frame_formats:
+
+BluFi 传输格式
+--------------
+
+手机 APP 与 ESP32 之间的 BluFi 通信格式定义如下:
+
+帧不分片情况下的标准格式 (8 bit):
+
++------------+---------------+-----------------+-------------+----------------+----------------+
+| LSB - Type | Frame Control | Sequence Number | Data Length | Data           | MSB - CheckSum |
++============+===============+=================+=============+================+================+
+| 1          | 1             | 1               | 1           | ${Data Length} | 2              |
++------------+---------------+-----------------+-------------+----------------+----------------+
+
+如果 **Frame Control** 帧中的 **More Frag** 使能,则 **Total Content Length** 为数据帧中剩余部分的总长度,用于报告终端需要分配多少内存。
+
+帧分片格式(8 bit):
+
++------------+--------------------+----------------+------------+-------------------------------------------+----------------+
+| LSB - Type | FrameControl(Frag) | SequenceNumber | DataLength | Data                                      | MSB - CheckSum |
++            +                    +                +            +----------------------+--------------------+                +
+|            |                    |                |            | Total Content Length | Content            |                |
++============+====================+================+============+======================+====================+================+
+| 1          | 1                  | 1              | 1          | 2                    | ${Data Length} - 2 | 2              |
++------------+--------------------+----------------+------------+----------------------+--------------------+----------------+
+
+通常情况下,控制帧不包含数据位,Ack 帧类型除外。
+
+Ack 帧格式(8 bit):
+
++------------------+---------------+-----------------+-------------+-----------------------+----------------+
+| LSB - Type (Ack) | Frame Control | SequenceNumber  | Data Length | Data                  | MSB - CheckSum |
++                  +               +                 +             +-----------------------+                +
+|                  |               |                 |             | Acked Sequence Number |                |
++==================+===============+=================+=============+=======================+================+
+| 1                | 1             | 1               | 1           | 1                     | 2              |
++------------------+---------------+-----------------+-------------+-----------------------+----------------+
+
+1. Type
+
+   类型域,占 1 byte。分为 Type 和 Subtype(子类型域)两部分, Type 占低 2 bit,Subtype 占高 6 bit。
+   
+   * 控制帧,暂不进行加密,可校验;
+   
+   * 数据帧,可加密,可校验。
+
+ **1.1 控制帧 (0x0b’00)** 
+
+  +------------------+-----------------------------------+----------------------------------------------------------------+----------------------------------------------------------------------+
+  | 控制帧 / 0x0b’00 | 含义                              | 解释                                                           | 备注                                                                 |
+  +==================+===================================+================================================================+======================================================================+
+  | 0x0b’000000      | Ack                               | 用来回复对方发的帧,                                           | Data 域使用1 byte Sequence 值,                                      |
+  |                  |                                   | Ack 帧的 Data 域使用回复对象帧的 Sequence 值。                 | 与恢复对象帧的Sequence 值相同。                                      |
+  +------------------+-----------------------------------+----------------------------------------------------------------+----------------------------------------------------------------------+
+  | 0x1b’000001      | Set ESP32 to the security mode.   | 通知 ESP32 发送数据时使用的安全模式,                          | Data 域占用 1 byte。                                                 |
+  |                  |                                   | 在该过程中可设置多次,每次设置后影响后续安全模式。             | 高 4 bit 为控制帧的安全模式,低 4bit 为数据帧的安全模式。            |
+  +                  +                                   + 在不设置的情况下,ESP32 默认控制帧和数据帧均为无校验、无加密。 +----------------------------------------------------------------------+
+  |                  |                                   | 手机到 ESP32 方向依赖于帧 Control 域。                         | b’0000:无校验、无加密;                                             |
+  +                  +                                   +                                                                +----------------------------------------------------------------------+
+  |                  |                                   |                                                                | b’0001:有校验、无加密;                                             |
+  +                  +                                   +                                                                +----------------------------------------------------------------------+
+  |                  |                                   |                                                                | b’0010:无校验、有加密;                                             |
+  +                  +                                   +                                                                +----------------------------------------------------------------------+
+  |                  |                                   |                                                                | b’0011:有校验、有加密。                                             |
+  +------------------+-----------------------------------+----------------------------------------------------------------+----------------------------------------------------------------------+
+  | 0x2b’000010      | Set the Wi-Fi opmode of ESP32.    | 设置 ESP32 的 Wi-Fi 模式,帧包含 opmode 信息。                 | data[0] 用于表示 opmode 类型,包括:                                 |
+  +                  +                                   +                                                                +----------------------------------------------------------------------+
+  |                  |                                   |                                                                | 0x00: NULL;                                                          |
+  +                  +                                   +                                                                +----------------------------------------------------------------------+
+  |                  |                                   |                                                                | 0x01: STA;                                                           |
+  +                  +                                   +                                                                +----------------------------------------------------------------------+
+  |                  |                                   |                                                                | 0x02: SoftAP;                                                        |
+  +                  +                                   +                                                                +----------------------------------------------------------------------+
+  |                  |                                   |                                                                | 0x03: SoftAP&STA.                                                    |
+  +                  +                                   +                                                                +----------------------------------------------------------------------+
+  |                  |                                   |                                                                | 如果设置有包含 AP,请尽量优先                                        |
+  |                  |                                   |                                                                | 设置 AP 模式的SSID/Password/Max Conn Number 等。                     |
+  +------------------+-----------------------------------+----------------------------------------------------------------+----------------------------------------------------------------------+
+  | 0x3b’000011      | Connect ESP32 to the AP.          | 通知 ESP32,必要的信息已经发送完毕,可以连接 AP。              | 不包含 Data 域。                                                     |
+  +------------------+-----------------------------------+----------------------------------------------------------------+----------------------------------------------------------------------+
+  | 0x4b’000100      | Disconnect ESP32 from  the AP.    | 通知 ESP32 断开与 AP 的连接                                    | 不包含 Data 域。                                                     |
+  +------------------+-----------------------------------+----------------------------------------------------------------+----------------------------------------------------------------------+
+  | 0x5b’000101      | Get the status of Wi-Fi.          | 获取 ESP32 的 Wi-Fi 模式和状态等信息。                         | 不包含 Data 域。                                                     |
+  |                  |                                   |                                                                | ESP32 收到此控制帧后,后续会通过 Wi-Fi 连接状态                      |
+  |                  |                                   |                                                                | 报告 (Wi-Fi Connection State Report) 数据帧来回复手机端当前          |
+  |                  |                                   |                                                                | 所处的 opmode、连接状态、SSID 等信息。提供给手机端的信息由应用决定。 |
+  +------------------+-----------------------------------+----------------------------------------------------------------+----------------------------------------------------------------------+
+  | 0x6b’000110      | Disconnect the STA device         | 处于 SoftAP 模式时,踢掉某个 STA 设备。                        | data[0~5] 为 STA 设备的 MAC 地址,                                   |
+  |                  | from the SoftAP in SoftAP mode.   |                                                                | 如有多个 STA,则 [6-11] 为第二个,依次类推。                         |
+  +------------------+-----------------------------------+----------------------------------------------------------------+----------------------------------------------------------------------+
+  | 0x7b'000111      | Get the version.                  |                                                                |                                                                      |
+  +------------------+-----------------------------------+----------------------------------------------------------------+----------------------------------------------------------------------+
+  | 0x8b’001000      | Tell ESP32 to disconnect          | 通知 ESP32 断开蓝牙连接。                                      | ESP32 收到该指令后主动断开蓝牙连接。                                 |
+  |                  | the BLE GATT link.                |                                                                |                                                                      |
+  +------------------+-----------------------------------+----------------------------------------------------------------+----------------------------------------------------------------------+
+  | 0x9b’001001      | Tell ESP32 to get the Wi-Fi list. | 通知 ESP32 扫描周围的 Wi-Fi 热点                               | 不包含 Data 域。                                                     |
+  |                  |                                   |                                                                | ESP32 收到此控制帧后,会发送包含 Wi-Fi 热点                          |
+  |                  |                                   |                                                                | 报告 (Wi-Fi List Report) 的数据帧回复                                |
+  |                  |                                   |                                                                | 手机端 ESP32 周围的 Wi-Fi 热点。                                     |
+  +------------------+-----------------------------------+----------------------------------------------------------------+----------------------------------------------------------------------+
+
+ **1.2 数据帧 (0x1b’01)**
+
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 数据帧        | 含义                                   | 解释                                           | 备注                                                 |
+  +===============+========================================+================================================+======================================================+
+  | 0x0 b’000000  | Negotiation data.                      | 用来发送协商数据,传输到应用层注册的回调函数。 | 数据长度与 Length 域有关。                           |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0x1 b’000001  | BSSID for STA mode.                    | STA 将要连接的 AP 的 BSSID(用于隐藏SSID)。   | 数据长度与 Length 域有关。                           |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 当传输方向为 ESP32 到手机时,                        |
+  |               |                                        |                                                | 表示向手机端提供信息。                               |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0x2 b’000010  | SSID for STA mode.                     | STA 将要连接的 AP 的 SSID。                    | 数据长度与 Length 域有关。                           |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 当传输方向为 ESP32 到手机时,                        |
+  |               |                                        |                                                | 表示向手机端提供信息。                               |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0x3 b’000011  | Password for STA mode.                 | STA 将要连接的 AP 的密码。                     | 数据长度与 Length 域有关。                           |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 当传输方向为 ESP32 到手机时,                        |
+  |               |                                        |                                                | 表示向手机端提供信息。                               |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0x4 b’000100  | SSID for SoftAP mode.                  | SoftAP 模式使用的 SSID。                       | 数据长度与 Length 域有关。                           |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 当传输方向为 ESP32 到手机时,                        |
+  |               |                                        |                                                | 表示向手机端提供信息。                               |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0x5 b’000101  | Password for SoftAPmode.               | SoftAP 模式使用的密码。                        | 数据长度与 Length 域有关。                           |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 当传输方向为 ESP32 到手机时,                        |
+  |               |                                        |                                                | 表示向手机端提供信息。                               |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0x6 b’000110  | Max connection number for SoftAP mode. | AP 模式的最大连接数。                          | data[0] 表示连接数的值,范围 1~4。                   |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 当传输方向为 ESP32 到手机时,                        |
+  |               |                                        |                                                | 表示向手机端提供信息。                               |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0x7b’000111   | Authentication mode for SoftAP mode.   | AP 模式的认证模式。                            | data[0]:                                            |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 0x00: OPEN;                                          |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 0x01: WEP;                                           |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 0x02: WPA_PSK;                                       |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 0x03: WPA2_PSK;                                      |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 0x04: WPA_WPA2_PSK.                                  |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 当传输方向为 ESP32 到手机时,                        |
+  |               |                                        |                                                | 表示向手机端提供信息。                               |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0x8b’001000   | Channel for SoftAP mode.               | SoftAP 模式的通道数量。                        | data[0] 表示通道的数量,范围 1~14。                  |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 当传输方向为 ESP32 到手机时,                        |
+  |               |                                        |                                                | 表示向手机端提供信息。                               |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0x9b’001001   | Username.                              | 使用企业级加密时,Client 端的用户名。          | 数据长度与 Length 域有关。                           |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0xab’001010   | CA certification.                      | 进行企业级加密时使用的 CA 证书。               | 数据长度与 Length 域有关,                           |
+  |               |                                        |                                                | 长度不够,可用分片。                                 |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0xbb’001011   | Client certification.                  | 进行企业级加密时,Client 端的证书。            | 数据长度与 Length 域有关,                           |
+  +               +                                        +------------------------------------------------+ 长度不够,可用分片。                                 +
+  |               |                                        | 可包含或不包含私钥,由证书内容决定。           |                                                      |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0xcb’001100   | Server certification.                  | 进行企业级加密时,Server 端的证书。            | 数据长度与 Length 域有关,                           |
+  +               +                                        +------------------------------------------------+ 长度不够,可用分片。                                 +
+  |               |                                        | 可包含或不包含私钥,由证书内容决定。           |                                                      |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0xdb’001101   | Client private key.                    | 进行企业级加密时,Client 端的私钥。            | 数据长度与 Length 域有关,                           |
+  |               |                                        |                                                | 长度不够,可用分片。                                 |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0xeb’001110   | Server private key.                    | 进行企业级加密时,Server 端的私钥。            | 数据长度与 Length 域有关,                           |
+  |               |                                        |                                                | 长度不够,可用分片。                                 |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0xf b’001111  | Wi-Fi connection state report.         | 通知手机 ESP32 的 Wi-Fi 状态,                 | data[0] 表示 opmode,包括:                          |
+  |               |                                        | 包括 STA状态和 SoftAP 状态,                   |                                                      |
+  |               |                                        | 用于手机配置 STA 连接时的通知,                |                                                      |
+  |               |                                        | 或有 STA 连接上 SoftAP 时的通知。              |                                                      |
+  +               +                                        +------------------------------------------------+------------------------------------------------------+
+  |               |                                        | 但收到手机询问 Wi-Fi 状态时,                  | 0x00: NULL;                                         |
+  +               +                                        + 除了回复此帧外,还可回复其他数据帧。           +------------------------------------------------------+
+  |               |                                        |                                                | 0x01: STA;                                           |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 0x02: SoftAP;                                        |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 0x03: SoftAP&STA                                     |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | data[1]:STA 的连接状态,                            |
+  |               |                                        |                                                | 0x0 表示处于连接状态,                               |
+  |               |                                        |                                                | 其他表示处于非连接状态;                             |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | data[2]:SoftAP 的连接状态,                         |
+  |               |                                        |                                                | 即表示有多少 STA 已经连接。                          |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | data[3] 及以后:为按照本协议格式 SSID\BSSID 等信息。 |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0x10 b’010000 | Version.                               |                                                | data[0]= great version                               |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | data[1]=sub version                                  |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0x11 B’010001 | Wi-Fi list.                            | 通知手机 ESP32 周围的 Wi-Fi 热点列表。         | 数据帧数据格式为 Length + RSSI + SSID,               |
+  |               |                                        |                                                | 数据较长时可分片发送。                               |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0x12 B’010010 | Report error.                          | 通知手机 BluFi 过程出现异常错误。              | 0x00: sequence error;                                |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 0x01: checksum error;                                |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 0x02: decrypt error;                                 |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 0x03: encrypt error;                                 |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 0x04: init security error;                           |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 0x05: dh malloc error;                               |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 0x06: dh param error;                                |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 0x07: read param  error;                             |
+  +               +                                        +                                                +------------------------------------------------------+
+  |               |                                        |                                                | 0x08: make public error.                             |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+  | 0x13 B’010011 | Custom data.                           | 用户发送或者接收自定义数据。                   | 数据较长时可分片发送。                               |
+  +---------------+----------------------------------------+------------------------------------------------+------------------------------------------------------+
+
+2. Frame Control
+
+   帧控制域,占 1 byte,每个 bit 表示不同含义。
+   
+   +----------------+-------------------------------------------------------------------------------------------------------------------------------+
+   | 位             | 含义                                                                                                                          |
+   +================+===============================================================================================================================+
+   | 0x01           | 表示帧是否加密。                                                                                                              |
+   +                +-------------------------------------------------------------------------------------------------------------------------------+
+   |                | 1 表示加密,0 表示未加密。                                                                                                    |
+   +                +-------------------------------------------------------------------------------------------------------------------------------+
+   |                | 加密部分帧括完整的 DATA 域加密之前的明文(不帧含末尾的校验)。                                                                |
+   +                +-------------------------------------------------------------------------------------------------------------------------------+
+   |                | 控制帧暂不加密,故控制帧此位为 0。                                                                                            |
+   +----------------+-------------------------------------------------------------------------------------------------------------------------------+
+   | 0x02           | 表示帧 Data 域结尾是否帧含校验(例如 SHA1,MD5,CRC等)需要校验的数据域包括 sequcne + data length + 明文 data。                 |
+   +                +-------------------------------------------------------------------------------------------------------------------------------+
+   |                | 控制帧和数据帧都可以包含校验位或不包含。                                                                                      |
+   +----------------+-------------------------------------------------------------------------------------------------------------------------------+
+   | 0x04           | 表示数据方向。                                                                                                                |
+   +                +-------------------------------------------------------------------------------------------------------------------------------+
+   |                | 0 表示手机发向 ESP32;                                                                                                        |
+   +                +-------------------------------------------------------------------------------------------------------------------------------+
+   |                | 1 表示 ESP32 发向手机。                                                                                                       |
+   +----------------+-------------------------------------------------------------------------------------------------------------------------------+
+   | 0x08           | 表示是否要求对方回复 ack。                                                                                                    |
+   +                +-------------------------------------------------------------------------------------------------------------------------------+
+   |                | 0 表示不要求;                                                                                                                |
+   +                +-------------------------------------------------------------------------------------------------------------------------------+
+   |                | 1 表示要求回复 ack。                                                                                                          |
+   +----------------+-------------------------------------------------------------------------------------------------------------------------------+
+   | 0x10           | 表示是否有后续的数据分片。                                                                                                    |
+   +                +-------------------------------------------------------------------------------------------------------------------------------+
+   |                | 0 表示此帧没有后续数据分片;                                                                                                  |
+   +                +-------------------------------------------------------------------------------------------------------------------------------+
+   |                | 1 表示还有后续数据分片,用来传输较长的数据。                                                                                  |
+   +                +-------------------------------------------------------------------------------------------------------------------------------+
+   |                | 如果是 Frag 帧,则告知当前 content 部分+后续 content 部分的总长度,位于 Data 域的前 2 字节(即最大支持 64K 的 content 数据)。 |
+   +----------------+-------------------------------------------------------------------------------------------------------------------------------+
+   | 0x10~0x80 保留 |                                                                                                                               |
+   +----------------+-------------------------------------------------------------------------------------------------------------------------------+
+
+
+3. Sequence Control
+
+   序列控制域。帧发送时,无论帧的类型是什么,序列 (Sequence) 都会自动加 1,用来防止重放攻击 (Replay Attack)。每次重现连接后,序列清零。
+   
+4. Length
+
+   Data 域的长度,不包含 CheckSum。
+   
+5. Data
+
+   不同的 Type 或 Subtype,Data 域的含义均不同。请参考上方表格。
+
+6. CheckSum
+
+   此域为 2 byte 的校验,用来校验『序列 + 数据长度 + 明文数据』。
+   
+ESP32 端的安全实现
+------------------
+
+1. 保证数据安全
+
+   为了保证 Wi-Fi SSID 和密码的传输过程是安全的,需要使用对称加密算法(例如 AES、DES等)对报文进行加密。在使用对称加密算法之前,需要使用非对称加密算法(DH、RSA、ECC 等)协商出(或生成出)一个共享密钥。
+
+2. 保证数据完整性
+
+   保证数据完整性,需要加入校验算法(例如 SHA1、MD5、CRC 等)。
+
+3. 身份安全(签名)
+
+   某些算法如 RSA 可以保证身份安全。有些算法如 DH,本身不能保证身份安全,需要添加其他算法来签名。
+
+4. 防止重放攻击 (Replay Attack)
+
+   加入帧发送序列(Sequence),并且序列参与数据校验。
+
+   在 ESP32 端的代码中,你可以决定和开发密钥协商等安全处理的流程参考上述流程图)。手机应用向 ESP32 发送协商数据,将传送给应用层处理。如果应用层不处理,可使用 BluFi 提供的 DH 加密算法来磋商密钥。应用层需向 BluFi 注册以下几个与安全相关的函数:
+
+.. code-block:: c
+
+   typedef void (*esp_blufi_negotiate_data_handler_t)(uint8_t *data, int len, uint8_t **output_data, int *output_len, bool *need_free);
+
+该函数用来接收协商期间的正常数据 (normal data),处理完成后,需要将待发送的数据使用 output_data 和 output_len 传出。
+   
+BluFi 会在调用完 negotiate_data_handler 后,发送 negotiate_data_handler 传出的 output_data。
+   
+这里的两个『*』,因为需要发出去的数据长度未知,所以需要函数自行分配 (malloc) 或者指向全局变量,通过 need_free 通知是否需要释放内存。
+.. code-block:: c
+
+   typedef int (* esp_blufi_encrypt_func_t)(uint8_t iv8, uint8_t *crypt_data, int cyprt_len);  
+  
+加密和解密的数据长度必须一致。其中 iv8 为帧的 8 bit 序列 (sequence),可作为 iv 的某 8 bit 来使用。
+  
+.. code-block:: c
+   
+   typedef int (* esp_blufi_decrypt_func_t)(uint8_t iv8, uint8_t *crypt_data, int crypt_len);
+
+加密和解密的数据长度必须一致。其中 iv8 为帧的 8 bit 序列 (sequence),可作为 iv 的某 8 bit 来使用。
+   
+.. code-block:: c
+   
+   typedef uint16_t (*esp_blufi_checksum_func_t)(uint8_t iv8, uint8_t *data, int len);
+   
+该函数用来计算 CheckSum,返回值为 CheckSum 的值。BluFi 会使用该函数返回值与包末尾的 CheckSum 做比较。
+      
+GATT 相关说明
+-------------
+
+UUID
+>>>>>
+
+BluFi Service UUID: 0xFFFF,16 bit
+
+BluFi (手机 -> ESP32) 特性:0xFF01,主要权限:可写
+
+BluFi (ESP32 -> 手机) 特性:0xFF02,主要权限:可读可通知
+
+.. note::
+
+       1. 目前 Ack 机制已经在该 Profile 协议中定义,但是还没有代码实现。
+       
+       2. 其他部分均已实现。
index a6a7d85661a9b6c8b584c06ba0fd48fcb8c2d601..661be7ee830afeaf9d97488eb67904ebd8e972d1 100644 (file)
@@ -1 +1,27 @@
-.. include:: ../../en/api-guides/index.rst
\ No newline at end of file
+API Guides
+**********
+
+.. toctree::
+   :maxdepth: 1
+
+   General Notes <general-notes>
+   Build System <build-system>
+   Deep Sleep Wake Stubs <deep-sleep-stub>
+   ESP32 Core Dump <core_dump>
+   Flash Encryption <../security/flash-encryption>
+   FreeRTOS SMP Changes <freertos-smp>
+   Thread Local Storage <thread-local-storage>
+   High Level Interrupts <hlinterrupts>
+   JTAG Debugging <jtag-debugging/index>
+   Bootloader <bootloader>
+   Partition Tables <partition-tables>
+   Secure Boot <../security/secure-boot>
+   ULP Coprocessor <ulp>
+   Unit Testing <unit-tests>
+   Application Level Tracing <app_trace>
+   Console Component <console>
+   ROM debug console <romconsole>
+   WiFi Driver <wifi>
+   Mesh Stack <mesh>
+   BluFi <blufi>
+   External SPI-connected RAM <external-ram>
\ No newline at end of file