gen_tcp参数总结

本文深入解析了Erlang中gen_tcp模块的各种参数设置,包括tos、tclass、priority、reuseaddr、keepalive等功能选项,以及sndbuf、recbuf、linger、nodelay等与性能密切相关的参数。同时探讨了这些参数对TCP连接的影响,为Erlang网络编程提供了详细的指导。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

动机

在用elixir 写 rpc server/client时, 需要对传入gen_tcp的参数做一些考量. 如, 部分参数应该允许用户修改, 比如sndbuf recbuf, 让用户根据使用场景调节, 部分参数应该屏蔽, 减少使用理解成本.
故, 深挖了一下gen_tcp的option

代码版本

文章中贴的文件和行号来源于如下代码版本

  • erlang: OTP-21.0.9

options

Available options for tcp:connect

inet.erl:723

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Available options for tcp:connect
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
connect_options() ->
    [tos, tclass, priority, reuseaddr, keepalive, linger, sndbuf, recbuf, nodelay,
     header, active, packet, packet_size, buffer, mode, deliver, line_delimiter,
     exit_on_close, high_watermark, low_watermark, high_msgq_watermark,
     low_msgq_watermark, send_timeout, send_timeout_close, delay_send, raw,
     show_econnreset, bind_to_device].

tos

type of service
下图来自tcp ip详解 卷1
clipboard.png

tclass

IPV6_TCLASS
{tclass, Integer}
Sets IPV6_TCLASS IP level options on platforms where this is implemented.
The behavior and allowed range varies between different systems.
The option is ignored on platforms where it is not implemented. Use with caution.
不知道具体含义, 忽略

priority

   SO_PRIORITY
          Set the protocol-defined priority for all packets to be sent
          on this socket.  Linux uses this value to order the networking
          queues: packets with a higher priority may be processed first
          depending on the selected device queueing discipline.  Setting
          a priority outside the range 0 to 6 requires the CAP_NET_ADMIN
          capability.

reuseaddr

   SO_REUSEPORT (since Linux 3.9)
          Permits multiple AF_INET or AF_INET6 sockets to be bound to an
          identical socket address.  This option must be set on each
          socket (including the first socket) prior to calling bind(2)
          on the socket.  To prevent port hijacking, all of the pro‐
          cesses binding to the same address must have the same effec‐
          tive UID.  This option can be employed with both TCP and UDP
          sockets.

          For TCP sockets, this option allows accept(2) load distribu‐
          tion in a multi-threaded server to be improved by using a dis‐
          tinct listener socket for each thread.  This provides improved
          load distribution as compared to traditional techniques such
          using a single accept(2)ing thread that distributes connec‐
          tions, or having multiple threads that compete to accept(2)
          from the same socket.

          For UDP sockets, the use of this option can provide better
          distribution of incoming datagrams to multiple processes (or
          threads) as compared to the traditional technique of having
          multiple processes compete to receive datagrams on the same
          socket.

keepalive

   SO_KEEPALIVE
          Enable sending of keep-alive messages on connection-oriented
          sockets.  Expects an integer boolean flag.
keepalive的可选参数和含义
root@1ba6f31f7bc3:/# cat /proc/sys/net/ipv4/tcp_keepalive_time
1800
the interval between the last data packet sent (simple ACKs are not considered data) and the first keepalive probe; after the connection is marked to need keepalive, this counter is not used any furthe
root@1ba6f31f7bc3:/# cat /proc/sys/net/ipv4/tcp_keepalive_intvl
75
the interval between subsequential keepalive probes, regardless of what the connection has exchanged in the meantime
root@1ba6f31f7bc3:/# cat /proc/sys/net/ipv4/tcp_keepalive_probes
9
the number of unacknowledged probes to send before considering the connection dead and notifying the application layer
主要问题:
  1. 没有穿透负载均衡器.
  2. 检测得太慢.
  3. 不知道应用状态.

linger

   SO_LINGER
          Sets or gets the SO_LINGER option.  The argument is a linger
          structure.

              struct linger {
                  int l_onoff;    /* linger active */
                  int l_linger;   /* how many seconds to linger for */
              };

          When enabled, a close(2) or shutdown(2) will not return until
          all queued messages for the socket have been successfully sent
          or the linger timeout has been reached.  Otherwise, the call
          returns immediately and the closing is done in the background.
          When the socket is closed as part of exit(2), it always
          lingers in the background.

close/shutdown前是否等待所有包都送达.

sndbuf recbuf buffer

   SO_SNDBUF
          Sets or gets the maximum socket send buffer in bytes.  The
          kernel doubles this value (to allow space for bookkeeping
          overhead) when it is set using setsockopt(2), and this doubled
          value is returned by getsockopt(2).  The default value is set
          by the /proc/sys/net/core/wmem_default file and the maximum
          allowed value is set by the /proc/sys/net/core/wmem_max file.
          The minimum (doubled) value for this option is 2048.
   SO_RCVBUF
          Sets or gets the maximum socket receive buffer in bytes.  The
          kernel doubles this value (to allow space for bookkeeping
          overhead) when it is set using setsockopt(2), and this doubled
          value is returned by getsockopt(2).  The default value is set
          by the /proc/sys/net/core/rmem_default file, and the maximum
          allowed value is set by the /proc/sys/net/core/rmem_max file.
          The minimum (doubled) value for this option is 256.

inet_drv.c:6708

case INET_OPT_SNDBUF:
    {
        arg.ival= get_int32 (curr);      curr += 4;
        proto   = SOL_SOCKET;
        type    = SO_SNDBUF;
        arg_ptr = (char*) (&arg.ival);
        arg_sz  = sizeof  ( arg.ival);

        /* Adjust the size of the user-level recv buffer, so it's not
           smaller than the kernel one: */
        if (desc->bufsz <= arg.ival)
        desc->bufsz  = arg.ival;
        break;
    }

可以看到, buffer是用户的缓存, 一定不小于内核buffer, 然而获得的buffer小于 recbuf, sdnbuf.
怀疑: 设置了recvbuf, sndbuf才会改变buffer.

nodelay

TCP_NODELAY

        DISCUSSION:
             The Nagle algorithm is generally as follows:

                  If there is unacknowledged data (i.e., SND.NXT >
                  SND.UNA), then the sending TCP buffers all user
                  data (regardless of the PSH bit), until the
                  outstanding data has been acknowledged or until
                  the TCP can send a full-sized segment (Eff.snd.MSS
                  bytes; see Section 4.2.2.6).

             Some applications (e.g., real-time display window
             updates) require that the Nagle algorithm be turned
             off, so small data segments can be streamed out at the
             maximum rate.

可以看到和延迟确认一起使用时会带来很大的延时.

header

http://erlang.org/doc/man/ine...
定长header, 处理定长header时可以一用.

active

用被动模式, 异步收发.

packet, raw

包头长度. 即用多少字节表示包长. raw 等同于 {packet, 0}

packet_size

包最大长度. 最大允许的包长.

mode

{mode, Mode :: binary | list}
Received Packet is delivered as defined by Mode.

deliver

{deliver, port | term}
When {active, true}, data is delivered on the form port : {S, {data, [H1,..Hsz | Data]}} or term : {tcp, S, [H1..Hsz | Data]}.

line_delimiter

{line_delimiter, Char}(TCP/IP sockets)
Sets the line delimiting character for line-oriented protocols (line). Defaults to $n.

exit_on_close

{exit_on_close, Boolean}
This option is set to true by default.
The only reason to set it to false is if you want to continue sending data to the socket after a close is detected, for example, if the peer uses gen_tcp:shutdown/2 to shut down the write side.

high_watermark, low_watermark, high_msgq_watermark,

 low_msgq_watermark

影响socket busy state的切换.
需要搞清楚几个问题:
socket busy state是什么, 譬如调用发送/接收有什么返回?
msgq data size 和 socket data size, socket data size 是否就是buffer?

send_timeout

发送超时时间, 默认无限等待

send_timeout_close

发送超时是否自动关闭.

delay_send

应用层并包. 默认关闭. 可以考虑开启.

show_econnreset

是否把RST当正常关闭.

bind_to_device

使用指定的设备(网卡)

参考资料

  1. http://erlang.org/doc/man/gen...
  2. http://man7.org/linux/man-pag...
  3. http://erlang.org/doc/man/ine...
  4. https://github.com/erlang/otp
  5. https://tools.ietf.org/html/r...
  6. https://www.ietf.org/rfc/rfc3...
  7. https://tools.ietf.org/html/r...
#include "Dri_BT.h" // 定义蓝牙状态 static bool bt_initialized = false; /* 定义esp32收到手机数据时的回调弱函数 */ void __attribute__((weak)) App_Communication_DealBtData(uint8_t *data, uint16_t dataLen) { } // 设置蓝牙名称 static char example_device_name[ESP_BLE_ADV_NAME_LEN_MAX] = "Zkevin_SmartHumidifier"; static uint8_t adv_config_done = 0; static uint16_t heart_rate_handle_table[HRS_IDX_NB]; static uint8_t test_manufacturer[3] = {'E', 'S', 'P'}; static uint8_t sec_service_uuid[16] = { /* LSB <--------------------------------------------------------------------------------> MSB */ // first uuid, 16bit, [12],[13] is the value 0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x18, 0x0D, 0x00, 0x00, }; // config adv data static esp_ble_adv_data_t heart_rate_adv_config = { .set_scan_rsp = false, .include_txpower = true, .min_interval = 0x0006, // slave connection min interval, Time = min_interval * 1.25 msec .max_interval = 0x0010, // slave connection max interval, Time = max_interval * 1.25 msec .appearance = 0x00, .manufacturer_len = 0, // TEST_MANUFACTURER_DATA_LEN, .p_manufacturer_data = NULL, //&test_manufacturer[0], .service_data_len = 0, .p_service_data = NULL, .service_uuid_len = sizeof(sec_service_uuid), .p_service_uuid = sec_service_uuid, .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT), }; // config scan response data static esp_ble_adv_data_t heart_rate_scan_rsp_config = { .set_scan_rsp = true, .include_name = true, .manufacturer_len = sizeof(test_manufacturer), .p_manufacturer_data = test_manufacturer, }; static esp_ble_adv_params_t heart_rate_adv_params = { .adv_int_min = 0x100, .adv_int_max = 0x100, .adv_type = ADV_TYPE_IND, .own_addr_type = BLE_ADDR_TYPE_RPA_PUBLIC, .channel_map = ADV_CHNL_ALL, .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY, }; struct gatts_profile_inst { esp_gatts_cb_t gatts_cb; uint16_t gatts_if; uint16_t app_id; uint16_t conn_id; uint16_t service_handle; esp_gatt_srvc_id_t service_id; uint16_t char_handle; esp_bt_uuid_t char_uuid; esp_gatt_perm_t perm; esp_gatt_char_prop_t property; uint16_t descr_handle; esp_bt_uuid_t descr_uuid; }; static void gatts_profile_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param); /* One gatt-based profile one app_id and one gatts_if, this array will store the gatts_if returned by ESP_GATTS_REG_EVT */ static struct gatts_profile_inst heart_rate_profile_tab[HEART_PROFILE_NUM] = { [HEART_PROFILE_APP_IDX] = { .gatts_cb = gatts_profile_event_handler, .gatts_if = ESP_GATT_IF_NONE, /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */ }, }; /* * Heart Rate PROFILE ATTRIBUTES **************************************************************************************** */ /// Heart Rate Sensor Service static const uint16_t heart_rate_svc = ESP_GATT_UUID_HEART_RATE_SVC; #define CHAR_DECLARATION_SIZE (sizeof(uint8_t)) static const uint16_t primary_service_uuid = ESP_GATT_UUID_PRI_SERVICE; static const uint16_t character_declaration_uuid = ESP_GATT_UUID_CHAR_DECLARE; static const uint16_t character_client_config_uuid = ESP_GATT_UUID_CHAR_CLIENT_CONFIG; static const uint8_t char_prop_notify = ESP_GATT_CHAR_PROP_BIT_NOTIFY; static const uint8_t char_prop_read = ESP_GATT_CHAR_PROP_BIT_READ; static const uint8_t char_prop_read_write = ESP_GATT_CHAR_PROP_BIT_WRITE | ESP_GATT_CHAR_PROP_BIT_READ; /// Heart Rate Sensor Service - Heart Rate Measurement Characteristic, notify static const uint16_t heart_rate_meas_uuid = ESP_GATT_HEART_RATE_MEAS; static const uint8_t heart_measurement_ccc[2] = {0x00, 0x00}; /// Heart Rate Sensor Service -Body Sensor Location characteristic, read static const uint16_t body_sensor_location_uuid = ESP_GATT_BODY_SENSOR_LOCATION; static const uint8_t body_sensor_loc_val[1] = {0x00}; /// Heart Rate Sensor Service - Heart Rate Control Point characteristic, write&read static const uint16_t heart_rate_ctrl_point = ESP_GATT_HEART_RATE_CNTL_POINT; static const uint8_t heart_ctrl_point[1] = {0x00}; /// Full HRS Database Description - Used to add attributes into the database static const esp_gatts_attr_db_t heart_rate_gatt_db[HRS_IDX_NB] = { // Heart Rate Service Declaration [HRS_IDX_SVC] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&primary_service_uuid, ESP_GATT_PERM_READ, sizeof(uint16_t), sizeof(heart_rate_svc), (uint8_t *)&heart_rate_svc}}, // Heart Rate Measurement Characteristic Declaration [HRS_IDX_HR_MEAS_CHAR] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ, CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_notify}}, // Heart Rate Measurement Characteristic Value [HRS_IDX_HR_MEAS_VAL] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&heart_rate_meas_uuid, ESP_GATT_PERM_READ, HRPS_HT_MEAS_MAX_LEN, 0, NULL}}, // Heart Rate Measurement Characteristic - Client Characteristic Configuration Descriptor [HRS_IDX_HR_MEAS_NTF_CFG] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_client_config_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE, sizeof(uint16_t), sizeof(heart_measurement_ccc), (uint8_t *)heart_measurement_ccc}}, // Body Sensor Location Characteristic Declaration [HRS_IDX_BOBY_SENSOR_LOC_CHAR] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ, CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read}}, // Body Sensor Location Characteristic Value [HRS_IDX_BOBY_SENSOR_LOC_VAL] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&body_sensor_location_uuid, ESP_GATT_PERM_READ_ENCRYPTED, sizeof(uint8_t), sizeof(body_sensor_loc_val), (uint8_t *)body_sensor_loc_val}}, // Heart Rate Control Point Characteristic Declaration [HRS_IDX_HR_CTNL_PT_CHAR] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ, CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read_write}}, // Heart Rate Control Point Characteristic Value [HRS_IDX_HR_CTNL_PT_VAL] = {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&heart_rate_ctrl_point, ESP_GATT_PERM_WRITE_ENCRYPTED | ESP_GATT_PERM_READ_ENCRYPTED, sizeof(uint8_t), sizeof(heart_ctrl_point), (uint8_t *)heart_ctrl_point}}, }; static char *esp_key_type_to_str(esp_ble_key_type_t key_type) { char *key_str = NULL; switch (key_type) { case ESP_LE_KEY_NONE: key_str = "ESP_LE_KEY_NONE"; break; case ESP_LE_KEY_PENC: key_str = "ESP_LE_KEY_PENC"; break; case ESP_LE_KEY_PID: key_str = "ESP_LE_KEY_PID"; break; case ESP_LE_KEY_PCSRK: key_str = "ESP_LE_KEY_PCSRK"; break; case ESP_LE_KEY_PLK: key_str = "ESP_LE_KEY_PLK"; break; case ESP_LE_KEY_LLK: key_str = "ESP_LE_KEY_LLK"; break; case ESP_LE_KEY_LENC: key_str = "ESP_LE_KEY_LENC"; break; case ESP_LE_KEY_LID: key_str = "ESP_LE_KEY_LID"; break; case ESP_LE_KEY_LCSRK: key_str = "ESP_LE_KEY_LCSRK"; break; default: key_str = "INVALID BLE KEY TYPE"; break; } return key_str; } static char *esp_auth_req_to_str(esp_ble_auth_req_t auth_req) { char *auth_str = NULL; switch (auth_req) { case ESP_LE_AUTH_NO_BOND: auth_str = "ESP_LE_AUTH_NO_BOND"; break; case ESP_LE_AUTH_BOND: auth_str = "ESP_LE_AUTH_BOND"; break; case ESP_LE_AUTH_REQ_MITM: auth_str = "ESP_LE_AUTH_REQ_MITM"; break; case ESP_LE_AUTH_REQ_BOND_MITM: auth_str = "ESP_LE_AUTH_REQ_BOND_MITM"; break; case ESP_LE_AUTH_REQ_SC_ONLY: auth_str = "ESP_LE_AUTH_REQ_SC_ONLY"; break; case ESP_LE_AUTH_REQ_SC_BOND: auth_str = "ESP_LE_AUTH_REQ_SC_BOND"; break; case ESP_LE_AUTH_REQ_SC_MITM: auth_str = "ESP_LE_AUTH_REQ_SC_MITM"; break; case ESP_LE_AUTH_REQ_SC_MITM_BOND: auth_str = "ESP_LE_AUTH_REQ_SC_MITM_BOND"; break; default: auth_str = "INVALID BLE AUTH REQ"; break; } return auth_str; } static void show_bonded_devices(void) { int dev_num = esp_ble_get_bond_device_num(); if (dev_num == 0) { ESP_LOGI(GATTS_TABLE_TAG, "Bonded devices number zero\n"); return; } esp_ble_bond_dev_t *dev_list = (esp_ble_bond_dev_t *)malloc(sizeof(esp_ble_bond_dev_t) * dev_num); if (!dev_list) { ESP_LOGI(GATTS_TABLE_TAG, "malloc failed, return\n"); return; } esp_ble_get_bond_device_list(&dev_num, dev_list); ESP_LOGI(GATTS_TABLE_TAG, "Bonded devices number %d", dev_num); for (int i = 0; i < dev_num; i++) { ESP_LOGI(GATTS_TABLE_TAG, "[%u] addr_type %u, addr " ESP_BD_ADDR_STR "", i, dev_list[i].bd_addr_type, ESP_BD_ADDR_HEX(dev_list[i].bd_addr)); } free(dev_list); } static void __attribute__((unused)) remove_all_bonded_devices(void) { int dev_num = esp_ble_get_bond_device_num(); if (dev_num == 0) { ESP_LOGI(GATTS_TABLE_TAG, "Bonded devices number zero\n"); return; } esp_ble_bond_dev_t *dev_list = (esp_ble_bond_dev_t *)malloc(sizeof(esp_ble_bond_dev_t) * dev_num); if (!dev_list) { ESP_LOGI(GATTS_TABLE_TAG, "malloc failed, return\n"); return; } esp_ble_get_bond_device_list(&dev_num, dev_list); for (int i = 0; i < dev_num; i++) { esp_ble_remove_bond_device(dev_list[i].bd_addr); } free(dev_list); } static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) { ESP_LOGV(GATTS_TABLE_TAG, "GAP_EVT, event %d", event); switch (event) { case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: adv_config_done &= (~SCAN_RSP_CONFIG_FLAG); if (adv_config_done == 0) { esp_ble_gap_start_advertising(&heart_rate_adv_params); } break; case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: adv_config_done &= (~ADV_CONFIG_FLAG); if (adv_config_done == 0) { esp_ble_gap_start_advertising(&heart_rate_adv_params); } break; case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: // advertising start complete event to indicate advertising start successfully or failed if (param->adv_start_cmpl.status != ESP_BT_STATUS_SUCCESS) { ESP_LOGE(GATTS_TABLE_TAG, "Advertising start failed, status %x", param->adv_start_cmpl.status); break; } ESP_LOGI(GATTS_TABLE_TAG, "Advertising start successfully"); break; case ESP_GAP_BLE_PASSKEY_REQ_EVT: /* passkey request event */ ESP_LOGI(GATTS_TABLE_TAG, "Passkey request"); /* Call the following function to input the passkey which is displayed on the remote device */ // esp_ble_passkey_reply(heart_rate_profile_tab[HEART_PROFILE_APP_IDX].remote_bda, true, 0x00); break; case ESP_GAP_BLE_OOB_REQ_EVT: { ESP_LOGI(GATTS_TABLE_TAG, "OOB request"); uint8_t tk[16] = {1}; // If you paired with OOB, both devices need to use the same tk esp_ble_oob_req_reply(param->ble_security.ble_req.bd_addr, tk, sizeof(tk)); break; } case ESP_GAP_BLE_LOCAL_IR_EVT: /* BLE local IR event */ ESP_LOGI(GATTS_TABLE_TAG, "Local identity root"); break; case ESP_GAP_BLE_LOCAL_ER_EVT: /* BLE local ER event */ ESP_LOGI(GATTS_TABLE_TAG, "Local encryption root"); break; case ESP_GAP_BLE_NC_REQ_EVT: /* The app will receive this evt when the IO has DisplayYesNO capability and the peer device IO also has DisplayYesNo capability. show the passkey number to the user to confirm it with the number displayed by peer device. */ esp_ble_confirm_reply(param->ble_security.ble_req.bd_addr, true); ESP_LOGI(GATTS_TABLE_TAG, "Numeric Comparison request, passkey %" PRIu32, param->ble_security.key_notif.passkey); break; case ESP_GAP_BLE_SEC_REQ_EVT: /* send the positive(true) security response to the peer device to accept the security request. If not accept the security request, should send the security response with negative(false) accept value*/ esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, true); break; case ESP_GAP_BLE_PASSKEY_NOTIF_EVT: /// the app will receive this evt when the IO has Output capability and the peer device IO has Input capability. /// show the passkey number to the user to input it in the peer device. ESP_LOGI(GATTS_TABLE_TAG, "Passkey notify, passkey %06" PRIu32, param->ble_security.key_notif.passkey); break; case ESP_GAP_BLE_KEY_EVT: // shows the ble key info share with peer device to the user. ESP_LOGI(GATTS_TABLE_TAG, "Key exchanged, key_type %s", esp_key_type_to_str(param->ble_security.ble_key.key_type)); break; case ESP_GAP_BLE_AUTH_CMPL_EVT: { esp_bd_addr_t bd_addr; memcpy(bd_addr, param->ble_security.auth_cmpl.bd_addr, sizeof(esp_bd_addr_t)); ESP_LOGI(GATTS_TABLE_TAG, "Authentication complete, addr_type %u, addr " ESP_BD_ADDR_STR "", param->ble_security.auth_cmpl.addr_type, ESP_BD_ADDR_HEX(bd_addr)); if (!param->ble_security.auth_cmpl.success) { ESP_LOGI(GATTS_TABLE_TAG, "Pairing failed, reason 0x%x", param->ble_security.auth_cmpl.fail_reason); } else { ESP_LOGI(GATTS_TABLE_TAG, "Pairing successfully, auth_mode %s", esp_auth_req_to_str(param->ble_security.auth_cmpl.auth_mode)); } show_bonded_devices(); break; } case ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT: { ESP_LOGD(GATTS_TABLE_TAG, "Bond device remove, status %d, device " ESP_BD_ADDR_STR "", param->remove_bond_dev_cmpl.status, ESP_BD_ADDR_HEX(param->remove_bond_dev_cmpl.bd_addr)); break; } case ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT: if (param->local_privacy_cmpl.status != ESP_BT_STATUS_SUCCESS) { ESP_LOGE(GATTS_TABLE_TAG, "Local privacy config failed, status %x", param->local_privacy_cmpl.status); break; } ESP_LOGI(GATTS_TABLE_TAG, "Local privacy config successfully"); esp_err_t ret = esp_ble_gap_config_adv_data(&heart_rate_adv_config); if (ret) { ESP_LOGE(GATTS_TABLE_TAG, "config adv data failed, error code = %x", ret); } else { adv_config_done |= ADV_CONFIG_FLAG; } ret = esp_ble_gap_config_adv_data(&heart_rate_scan_rsp_config); if (ret) { ESP_LOGE(GATTS_TABLE_TAG, "config adv data failed, error code = %x", ret); } else { adv_config_done |= SCAN_RSP_CONFIG_FLAG; } break; default: break; } } static void gatts_profile_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) { ESP_LOGV(GATTS_TABLE_TAG, "event = %x", event); switch (event) { case ESP_GATTS_REG_EVT: ESP_LOGI(GATTS_TABLE_TAG, "GATT server register, status %d, app_id %d, gatts_if %d", param->reg.status, param->reg.app_id, gatts_if); esp_ble_gap_set_device_name(example_device_name); // generate a resolvable random address esp_ble_gap_config_local_privacy(true); esp_ble_gatts_create_attr_tab(heart_rate_gatt_db, gatts_if, HRS_IDX_NB, HEART_RATE_SVC_INST_ID); break; case ESP_GATTS_READ_EVT: break; case ESP_GATTS_WRITE_EVT: ESP_LOGI(GATTS_TABLE_TAG, "Characteristic write, value "); ESP_LOG_BUFFER_HEX(GATTS_TABLE_TAG, param->write.value, param->write.len); App_Communication_DealBtData(param->write.value, param->write.len); break; case ESP_GATTS_EXEC_WRITE_EVT: break; case ESP_GATTS_MTU_EVT: break; case ESP_GATTS_CONF_EVT: break; case ESP_GATTS_UNREG_EVT: break; case ESP_GATTS_DELETE_EVT: break; case ESP_GATTS_START_EVT: break; case ESP_GATTS_STOP_EVT: break; case ESP_GATTS_CONNECT_EVT: ESP_LOGI(GATTS_TABLE_TAG, "Connected, conn_id %u, remote " ESP_BD_ADDR_STR "", param->connect.conn_id, ESP_BD_ADDR_HEX(param->connect.remote_bda)); /* start security connect with peer device when receive the connect event sent by the master */ esp_ble_set_encryption(param->connect.remote_bda, ESP_BLE_SEC_ENCRYPT_MITM); break; case ESP_GATTS_DISCONNECT_EVT: ESP_LOGI(GATTS_TABLE_TAG, "Disconnected, remote " ESP_BD_ADDR_STR ", reason 0x%x", ESP_BD_ADDR_HEX(param->disconnect.remote_bda), param->disconnect.reason); /* start advertising again when missing the connect */ esp_ble_gap_start_advertising(&heart_rate_adv_params); break; case ESP_GATTS_OPEN_EVT: break; case ESP_GATTS_CANCEL_OPEN_EVT: break; case ESP_GATTS_CLOSE_EVT: break; case ESP_GATTS_LISTEN_EVT: break; case ESP_GATTS_CONGEST_EVT: break; case ESP_GATTS_CREAT_ATTR_TAB_EVT: { if (param->create.status == ESP_GATT_OK) { if (param->add_attr_tab.num_handle == HRS_IDX_NB) { ESP_LOGI(GATTS_TABLE_TAG, "Attribute table create successfully, num_handle %x", param->add_attr_tab.num_handle); memcpy(heart_rate_handle_table, param->add_attr_tab.handles, sizeof(heart_rate_handle_table)); esp_ble_gatts_start_service(heart_rate_handle_table[HRS_IDX_SVC]); } else { ESP_LOGE(GATTS_TABLE_TAG, "Attribute table create abnormally, num_handle (%d) doesn't equal to HRS_IDX_NB(%d)", param->add_attr_tab.num_handle, HRS_IDX_NB); } } else { ESP_LOGE(GATTS_TABLE_TAG, "Attribute table create failed, error code = %x", param->create.status); } break; } default: break; } } static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) { /* If event is register event, store the gatts_if for each profile */ if (event == ESP_GATTS_REG_EVT) { if (param->reg.status == ESP_GATT_OK) { heart_rate_profile_tab[HEART_PROFILE_APP_IDX].gatts_if = gatts_if; } else { ESP_LOGI(GATTS_TABLE_TAG, "Reg app failed, app_id %04x, status %d", param->reg.app_id, param->reg.status); return; } } do { int idx; for (idx = 0; idx < HEART_PROFILE_NUM; idx++) { if (gatts_if == ESP_GATT_IF_NONE || /* ESP_GATT_IF_NONE, not specify a certain gatt_if, need to call every profile cb function */ gatts_if == heart_rate_profile_tab[idx].gatts_if) { if (heart_rate_profile_tab[idx].gatts_cb) { heart_rate_profile_tab[idx].gatts_cb(event, gatts_if, param); } } } } while (0); } /** * @brief 初始化蓝牙模块 * */ void Dri_BT_Init(void) { // 避免重复初始化 if (bt_initialized) { ESP_LOGI(GATTS_TABLE_TAG, "Bluetooth already initialized"); return; } esp_err_t ret; // 获取当前蓝牙状态 esp_bt_controller_status_t bt_status = esp_bt_controller_get_status(); // 蓝牙未被初始化 if (bt_status == ESP_BT_CONTROLLER_STATUS_IDLE) { // 初始化NVS.为了存入蓝牙连接信息; ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { ESP_ERROR_CHECK(nvs_flash_erase()); ret = nvs_flash_init(); } ESP_ERROR_CHECK(ret); // 释放经典蓝牙部署 ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT)); // 初始化蓝牙硬件配置 esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); esp_bt_controller_init(&bt_cfg); esp_bt_controller_enable(ESP_BT_MODE_BLE); // 初始化蓝牙应用层软件配置 esp_bluedroid_init(); esp_bluedroid_enable(); } // 蓝牙未初始化 if (!bt_initialized) { // 注册回调函数 esp_ble_gatts_register_callback(gatts_event_handler); esp_ble_gap_register_callback(gap_event_handler); esp_ble_gatts_app_register(ESP_HEART_RATE_APP_ID); // 设置安全参数,未来传输数据需要加密,采用非对称加密方式(公钥和私钥) esp_ble_auth_req_t auth_req = ESP_LE_AUTH_REQ_SC_MITM_BOND; // bonding with peer device after authentication esp_ble_io_cap_t iocap = ESP_IO_CAP_NONE; // set the IO capability to No output No input uint8_t key_size = 16; // the key size should be 7~16 bytes uint8_t init_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK; uint8_t rsp_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK; // 安全密钥 uint32_t passkey = 123456; uint8_t auth_option = ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_DISABLE; uint8_t oob_support = ESP_BLE_OOB_DISABLE; esp_ble_gap_set_security_param(ESP_BLE_SM_SET_STATIC_PASSKEY, &passkey, sizeof(uint32_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &auth_req, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_MAX_KEY_SIZE, &key_size, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH, &auth_option, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_OOB_SUPPORT, &oob_support, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_SET_INIT_KEY, &init_key, sizeof(uint8_t)); esp_ble_gap_set_security_param(ESP_BLE_SM_SET_RSP_KEY, &rsp_key, sizeof(uint8_t)); } bt_initialized = true; } #include "Dri_Wifi.h" // 蓝牙的两种情况 // 二维码扫描前需要配网低功耗蓝牙和自定义GATT低功耗蓝牙 // WIFI配网成功后,只需要自定义GATT低功耗蓝牙 typedef enum { BT_MODE_GATT, // GATT服务模式 BT_MODE_DUAL // 双模式(同时支持配网和GATT) } bt_mode_t; // 默认双模式 static bt_mode_t current_bt_mode = BT_MODE_DUAL; static wifi_conn wifi_success_cb; static const char *TAG = "WIFI"; const int WIFI_CONNECTED_EVENT = BIT0; static EventGroupHandle_t wifi_event_group; #define PROV_QR_VERSION "v1" #define PROV_TRANSPORT_BLE "ble" #define QRCODE_BASE_URL "https://espressif.github.io/esp-jumpstart/qrcode.html" // WIFI各种事件的回调函数 static void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { // 记录失败次数 static int retries; // 记录WIFI连接失败次数 static uint8_t wifi_conn_retries = 0; if (event_base == WIFI_PROV_EVENT) // WIFI配置事件 { switch (event_id) { case WIFI_PROV_START: ESP_LOGI(TAG, "Provisioning started"); break; case WIFI_PROV_CRED_RECV: { wifi_sta_config_t *wifi_sta_cfg = (wifi_sta_config_t *)event_data; ESP_LOGI(TAG, "Received Wi-Fi credentials" "\n\tSSID : %s\n\tPassword : %s", (const char *)wifi_sta_cfg->ssid, (const char *)wifi_sta_cfg->password); break; } case WIFI_PROV_CRED_FAIL: { wifi_prov_sta_fail_reason_t *reason = (wifi_prov_sta_fail_reason_t *)event_data; ESP_LOGE(TAG, "Provisioning failed!\n\tReason : %s" "\n\tPlease reset to factory and retry provisioning", (*reason == WIFI_PROV_STA_AUTH_ERROR) ? "Wi-Fi station authentication failed" : "Wi-Fi access-point not found"); retries++; if (retries >= 5) { ESP_LOGI(TAG, "Failed to connect with provisioned AP, resetting provisioned credentials"); wifi_prov_mgr_reset_sm_state_on_failure(); retries = 0; } break; } case WIFI_PROV_CRED_SUCCESS: ESP_LOGI(TAG, "Provisioning successful"); retries = 0; break; case WIFI_PROV_END: // 配置完成后,取消初始化管理器 wifi_prov_mgr_deinit(); break; default: break; } } else if (event_base == WIFI_EVENT) // WIFI事件 { switch (event_id) { case WIFI_EVENT_STA_START: esp_wifi_connect(); break; case WIFI_EVENT_STA_DISCONNECTED: ESP_LOGI(TAG, "Disconnected. Connecting to the AP again..."); wifi_conn_retries++; if (wifi_conn_retries >= 10) { // 重置WIFI配置 wifi_prov_mgr_reset_provisioning(); // 重启芯片 esp_restart(); } esp_wifi_connect(); break; default: break; } } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) // 连接成功 { // 重置记录WIFI连接失败次数 wifi_conn_retries = 0; // 引用运行回调函数代码 wifi_success_cb(); ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data; ESP_LOGI(TAG, "Connected with IP Address:" IPSTR, IP2STR(&event->ip_info.ip)); xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_EVENT); } else if (event_base == PROTOCOMM_TRANSPORT_BLE_EVENT) // 蓝牙事件 { switch (event_id) { case PROTOCOMM_TRANSPORT_BLE_CONNECTED: ESP_LOGI(TAG, "BLE transport: Connected!"); break; case PROTOCOMM_TRANSPORT_BLE_DISCONNECTED: ESP_LOGI(TAG, "BLE transport: Disconnected!"); break; default: break; } } } static void wifi_init_sta(void) { /* Start Wi-Fi in station mode */ ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); ESP_ERROR_CHECK(esp_wifi_start()); } static void get_device_service_name(char *service_name, size_t max) { uint8_t eth_mac[6]; const char *ssid_prefix = "PROV_"; esp_wifi_get_mac(WIFI_IF_STA, eth_mac); snprintf(service_name, max, "%s%02X%02X%02X", ssid_prefix, eth_mac[3], eth_mac[4], eth_mac[5]); } esp_err_t custom_prov_data_handler(uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen, void *priv_data) { if (inbuf) { ESP_LOGI(TAG, "Received data: %.*s", inlen, (char *)inbuf); } char response[] = "SUCCESS"; *outbuf = (uint8_t *)strdup(response); if (*outbuf == NULL) { ESP_LOGE(TAG, "System out of memory"); return ESP_ERR_NO_MEM; } *outlen = strlen(response) + 1; /* +1 for NULL terminating byte */ return ESP_OK; } static void wifi_prov_print_qr(const char *name, const char *username, const char *pop, const char *transport) { if (!name || !transport) { ESP_LOGW(TAG, "Cannot generate QR code payload. Data missing."); return; } char payload[150] = {0}; snprintf(payload, sizeof(payload), "{\"ver\":\"%s\",\"name\":\"%s\"" ",\"transport\":\"%s\"}", PROV_QR_VERSION, name, transport); ESP_LOGI(TAG, "Scan this QR code from the provisioning application for Provisioning."); esp_qrcode_config_t cfg = ESP_QRCODE_CONFIG_DEFAULT(); esp_qrcode_generate(&cfg, payload); ESP_LOGI(TAG, "If QR code is not visible, copy paste the below URL in a browser.\n%s?data=%s", QRCODE_BASE_URL, payload); } /** * @brief 初始化WIFI模块 * */ void Dri_Wifi_Init(wifi_conn wifi_conn_success) { // 赋值回调函数 wifi_success_cb = wifi_conn_success; // 初始化NVS,用于保存WIFI名称于Flash esp_err_t ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { ESP_ERROR_CHECK(nvs_flash_erase()); ESP_ERROR_CHECK(nvs_flash_init()); } // 初始化TCP/IP ESP_ERROR_CHECK(esp_netif_init()); // 创建事件循环组 ESP_ERROR_CHECK(esp_event_loop_create_default()); wifi_event_group = xEventGroupCreate(); // 注册各种事件回调函数 ESP_ERROR_CHECK(esp_event_handler_register(WIFI_PROV_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL)); ESP_ERROR_CHECK(esp_event_handler_register(PROTOCOMM_TRANSPORT_BLE_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL)); ESP_ERROR_CHECK(esp_event_handler_register(PROTOCOMM_SECURITY_SESSION_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL)); ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL)); ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL)); // 根据TCP/IP网络协议,初始化WIFI esp_netif_create_default_wifi_sta(); wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); ESP_ERROR_CHECK(esp_wifi_init(&cfg)); // 初始化自定义GATT蓝牙 Dri_BT_Init(); // 配网配置信息 wifi_prov_mgr_config_t config = { .scheme = wifi_prov_scheme_ble, .scheme_event_handler = WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM, }; // 配网初始化 ESP_ERROR_CHECK(wifi_prov_mgr_init(config)); bool provisioned = false; // wifi_prov_mgr_reset_provisioning(); // 检查是否配网 ESP_ERROR_CHECK(wifi_prov_mgr_is_provisioned(&provisioned)); // 根据是否配网,做对应操作 // 没有配网 if (!provisioned) { ESP_LOGI(TAG, "Starting provisioning"); // 配网模式:同时支持配网和GATT current_bt_mode = BT_MODE_DUAL; // WIFI设备名称 char service_name[12]; get_device_service_name(service_name, sizeof(service_name)); // 无安全设置 const char *service_key = NULL; // WIFI设备唯一标识 uint8_t custom_service_uuid[] = { /* LSB <--------------------------------------- * ---------------------------------------> MSB */ 0xb4, 0xdf, 0x5a, 0x1c, 0x3f, 0x6b, 0xf4, 0xbf, 0xea, 0x4a, 0x82, 0x03, 0x04, 0x90, 0x1a, 0x02, }; wifi_prov_scheme_ble_set_service_uuid(custom_service_uuid); // 创建WIFI设备节点信息 wifi_prov_mgr_endpoint_create("custom-data"); // 启动配网设备 wifi_prov_security_t security = WIFI_PROV_SECURITY_0; ESP_ERROR_CHECK(wifi_prov_mgr_start_provisioning(security, (const void *)NULL, service_name, service_key)); // 在网络中进行设备注册 wifi_prov_mgr_endpoint_register("custom-data", custom_prov_data_handler, NULL); // 打印二维码 wifi_prov_print_qr(service_name, NULL, NULL, PROV_TRANSPORT_BLE); // 启动双服务广播 start_dual_service_advertising(); } else { ESP_LOGI(TAG, "Already provisioned, starting Wi-Fi STA"); // 已配网:仅GATT模式 current_bt_mode = BT_MODE_GATT; // 配网初始化 wifi_prov_mgr_deinit(); // 启动WIFI wifi_init_sta(); // 启动GATT服务广播 esp_ble_gap_start_advertising(&heart_rate_adv_params); } // 等待WIFI连接成功 xEventGroupWaitBits(wifi_event_group, WIFI_CONNECTED_EVENT, true, true, portMAX_DELAY); } 蓝牙的两种情况怎么实现
最新发布
07-08
<think>我们有两个蓝牙模式:双模式(同时支持配网和GATT)和仅GATT模式。 在双模式下,设备同时运行两个服务:一个是用于WiFi配网的BLE服务(使用ESP-IDF的wifi_prov_mgr组件),另一个是自定义的GATT服务(用于设备控制)。 在仅GATT模式下,设备只运行自定义的GATT服务。 问题在于:如何实现双模式?即同时运行两个BLE服务(配网服务和自定义GATT服务)? 解决方案: 1. 在未配网时,设备启动双模式:同时启动配网服务和自定义GATT服务。 2. 在已配网时,设备启动仅GATT模式:只运行自定义GATT服务。 但是,同时运行两个BLE服务(两个GATT服务)在同一个设备上需要解决以下问题: - 如何同时注册两个GATT服务? - 如何同时广播两个服务? 实际上,一个BLE设备可以同时包含多个服务(GATT服务是由多个特征值组成的集合)。因此,我们可以将配网服务(由wifi_prov_mgr组件提供)和我们的自定义GATT服务(心率服务)同时注册到同一个BLE设备上。 然而,配网服务在启动时会占用广播,因此我们需要在启动配网服务的同时启动我们的自定义服务广播。但注意,配网服务在启动时已经设置了广播数据,如果我们再设置自定义服务的广播,会覆盖配网服务的广播数据。 因此,我们需要在广播数据中包含两个服务的UUID。具体步骤如下: 步骤1:在双模式下,我们需要修改广播数据,同时包含配网服务的UUID和自定义GATT服务的UUID。 步骤2:在广播响应数据(scan response)中包含设备名称和制造商数据等。 但是,wifi_prov_mgr组件在启动配网服务时,会自动设置广播数据。因此,我们需要在配网服务启动后,再修改广播数据,将自定义服务的UUID也加进去。 然而,wifi_prov_mgr并没有提供直接修改广播数据的接口。所以我们需要在配网服务启动后,重新设置广播数据。 具体实现: 1. 初始化配网服务(wifi_prov_mgr_init, wifi_prov_mgr_start_provisioning)。 2. 在配网服务启动后,获取当前广播数据,然后修改广播数据,添加自定义服务的UUID。 3. 重新设置广播数据并开始广播。 但是,这样操作可能会干扰配网服务的工作,因为配网服务需要特定的广播数据(包含其服务UUID)才能被手机APP识别。 另一种思路:我们可以在配网服务的广播数据中同时包含自定义服务的UUID。这样,手机APP在扫描设备时,会同时看到两个服务。配网完成后,我们停止配网服务,只保留自定义服务。 然而,在配网过程中,配网服务需要处理连接和通信,同时我们的自定义服务也要处理连接和通信,这可能会引起资源冲突(例如,只有一个GATT接口可以处理连接事件?)。 实际上,ESP32支持多个GATT服务同时运行。我们可以同时注册配网服务的GATT profile和自定义GATT服务的profile。但是,广播数据中只能包含一个主要的服务UUID,或者一个服务UUID列表。 因此,我们可以将两个服务的UUID都加入到广播数据中。配网服务通常使用128位的UUID,而我们的自定义服务使用16位的UUID(心率服务0x180D)。我们可以将这两个UUID都加入到广播数据的服务UUID列表中。 具体步骤: 1. 在双模式下,先启动配网服务(wifi_prov_mgr_start_provisioning),此时配网服务会设置广播数据(只包含配网服务的UUID)。 2. 然后,我们修改广播数据,将自定义服务的UUID(心率服务0x180D)也加入进去。 3. 重新设置广播数据并开始广播。 注意:广播数据有长度限制(31字节),所以需要确保两个UUID能放进去。 配网服务的UUID是128位的(由wifi_prov_scheme_ble_set_service_uuid设置),而我们的自定义服务是16位的,所以两个UUID总共需要16+2=18字节(加上长度类型等),所以可以放进去。 修改广播数据的方法: - 使用esp_ble_gap_stop_advertising()停止当前的广播。 - 使用esp_ble_gap_config_adv_data()重新配置广播数据,将两个服务的UUID都加入。 - 使用esp_ble_gap_start_advertising()重新开始广播。 但是,配网服务在启动时已经注册了GATT服务,我们只需要在广播数据中加入自定义服务的UUID,这样手机就能看到两个服务。 然而,配网服务在运行过程中可能会重新设置广播数据(例如在断开连接后),这样就会覆盖我们修改的广播数据。所以我们需要在每次配网服务设置广播后,再重新修改广播数据。这需要修改配网组件的内部行为,不太可行。 另一种方案:我们可以在配网服务启动后,延迟一段时间再修改广播数据,并且在配网服务的事件回调中,监听广播设置完成的事件,然后再次修改广播数据。但这样可能会造成竞争条件。 考虑到配网过程是临时的(一旦配网成功,设备将不再需要配网服务),我们可以采用以下策略: - 在双模式下,我们优先保证配网服务的正常运行,因为配网是临时需求。配网服务启动后,我们不再修改其广播数据,而是让自定义服务使用扫描响应数据(scan response)来包含自己的UUID。 - 在广播数据中,我们只放配网服务的UUID(这是配网服务要求的),然后在扫描响应数据中加入自定义服务的UUID。这样,当手机扫描设备时,会先收到广播数据(包含配网服务UUID),然后发送扫描请求,设备回复扫描响应数据(包含自定义服务UUID)。这样手机就能同时发现两个服务。 但是,广播数据(advertising data)和扫描响应数据(scan response data)都有31字节的限制。配网服务的UUID已经占用了16字节,再加上一些标志位等,可能没有足够空间再放另一个UUID。而扫描响应数据中我们可以放设备名称、自定义服务的UUID等。 具体操作: 1. 在配网服务启动后,我们获取配网服务设置的广播数据,然后我们设置扫描响应数据,在扫描响应数据中加入自定义服务的UUID(16位)和完整的设备名称等。 2. 这样,当手机扫描时,会收到广播数据(配网服务UUID)和扫描响应数据(自定义服务UUID),手机就能发现两个服务。 步骤: - 初始化配网服务,并启动配网。 - 在配网服务启动后,我们调用一个函数来设置扫描响应数据(包含自定义服务的UUID)。 但是,如何知道配网服务已经设置好了广播数据?我们可以通过事件回调。配网服务在设置广播数据完成后,会触发一个事件吗?在gap_event_handler中,我们可以监听ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT事件。但是,这个事件是配网服务设置广播数据完成后触发的。 因此,我们可以在gap_event_handler中,当收到ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT事件时,判断当前是双模式,然后设置扫描响应数据(包含自定义服务的UUID)。 注意:在双模式下,我们需要在广播数据中保留配网服务的UUID,而在扫描响应数据中加入自定义服务的UUID。这样,广播数据不会被覆盖,同时扫描响应数据中包含了自定义服务的信息。 具体代码实现: 1. 在双模式标志下,我们设置一个状态,表示需要设置扫描响应数据。 2. 在gap_event_handler中: case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: // 如果是双模式,并且是配网服务设置的广播数据完成 if (current_bt_mode == BT_MODE_DUAL) { // 配置扫描响应数据 esp_ble_adv_data_t scan_rsp_data = { .set_scan_rsp = true, .include_name = true, .include_txpower = false, .service_uuid_len = sizeof(custom_service_uuid), // 自定义服务的UUID长度(16位,所以是2字节) .p_service_uuid = custom_service_uuid, // 自定义服务的UUID(心率服务:0x180D) .appearance = 0, .manufacturer_len = 0, .p_manufacturer_data = NULL, .service_data_len = 0, .p_service_data = NULL, }; esp_ble_gap_config_adv_data(&scan_rsp_data); } break; 3. 然后,在扫描响应数据设置完成事件(ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT)中,再开始广播。 但是,配网服务在设置广播数据后已经开始了广播,我们这里重新设置扫描响应数据会停止广播吗?不会,但我们需要重新开始广播吗?不需要,因为设置扫描响应数据后,广播仍然在进行,只是扫描响应数据更新了。 然而,根据ESP-IDF文档,调用esp_ble_gap_config_adv_data()设置扫描响应数据时,如果当前正在广播,则会停止广播,然后重新开始广播。所以我们需要在设置扫描响应数据后,重新开始广播。 但是,这样会中断配网服务吗?可能会,但配网服务应该能处理断开重连。 所以,我们可以在设置扫描响应数据后,重新开始广播。 具体步骤: - 在ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT事件中,设置扫描响应数据。 - 在ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT事件中,重新开始广播。 但是,这样会有一个问题:配网服务已经开始了广播,我们修改扫描响应数据后需要重新开始广播,这样就会导致设备断开连接(如果有连接的话)并重新广播。 因此,为了避免频繁断开,我们可以在设备未连接时(比如刚启动)进行设置。或者,我们可以在配网服务启动后,先停止广播,然后设置广播数据和扫描响应数据(同时包含两个服务的UUID),再开始广播。但这样需要知道配网服务设置的广播数据内容,然后修改它。 考虑到复杂性,我们可以采用另一种方法:在启动配网服务之前,我们先设置好广播数据和扫描响应数据(包含两个服务的UUID),然后再启动配网服务。这样,配网服务在启动时就不会覆盖广播数据。 但是,配网服务在启动时(wifi_prov_mgr_start_provisioning)会设置广播数据,所以会覆盖我们预先设置的广播数据。 因此,我们只能采用在配网服务设置广播数据后,再修改广播数据的方法。 综合权衡,我们决定: - 在双模式下,先让配网服务启动并设置广播数据(只包含配网服务UUID)。 - 然后,我们立即修改广播数据,将自定义服务的UUID也加入广播数据中(因为配网服务的UUID是128位的,自定义服务是16位的,所以广播数据中我们可以同时包含两个UUID)。 - 修改广播数据后,重新开始广播。 具体步骤: 1. 启动配网服务:wifi_prov_mgr_start_provisioning() 2. 在配网服务设置广播数据完成后,我们在gap事件中捕获ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT事件。 3. 在该事件中,我们构造新的广播数据,包含两个服务的UUID(配网服务的128位UUID和自定义服务的16位UUID)。 4. 调用esp_ble_gap_config_adv_data()设置新的广播数据,并设置一个标志,表示我们正在修改广播数据。 5. 在新的广播数据设置完成事件(ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT)中,我们开始广播。 但是,这里要注意,修改广播数据会停止当前的广播,所以我们需要重新开始广播。 代码结构: static uint8_t adv_config_done = 0; #define ADV_CONFIG_FLAG (1 << 0) #define SCAN_RSP_CONFIG_FLAG (1 << 1) // 在事件处理函数中: case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: if (current_bt_mode == BT_MODE_DUAL) { // 第一次是配网服务设置的广播数据,我们记录下配网服务的UUID // 然后,我们设置新的广播数据,包含配网服务的UUID和自定义服务的UUID if (adv_config_done == 0) { // 设置新的广播数据 esp_ble_adv_data_t adv_data = { .set_scan_rsp = false, .include_name = true, .include_txpower = true, .min_interval = 0x0006, .max_interval = 0x0010, .appearance = 0x00, .manufacturer_len = 0, .p_manufacturer_data = NULL, .service_data_len = 0, .p_service_data = NULL, .service_uuid_len = sizeof(full_service_uuids), // 两个服务的UUID总长度 .p_service_uuid = full_service_uuids, // 指向两个服务UUID的数组 .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT), }; esp_ble_gap_config_adv_data(&adv_data); adv_config_done |= ADV_CONFIG_FLAG; } else { // 新的广播数据设置完成,开始广播 esp_ble_gap_start_advertising(&heart_rate_adv_params); } } break; 其中,full_service_uuids是一个数组,包含两个服务的UUID:配网服务的128位UUID和自定义服务的16位UUID(0x180D)。注意:广播数据中的服务UUID列表是平铺的,即先放128位的UUID(16字节),再放16位的UUID(2字节)。 但是,配网服务的UUID是由wifi_prov_scheme_ble_set_service_uuid()设置的,我们可以获取到吗?在代码中,我们之前已经设置了配网服务的UUID(custom_service_uuid),所以我们可以直接使用。 因此,我们可以这样构造full_service_uuids: uint8_t full_service_uuids[16+2]; // 128位UUID+16位UUID memcpy(full_service_uuids, custom_service_uuid, 16); // 配网服务UUID full_service_uuids[16] = 0x0D; // 心率服务的16位UUID的低字节 full_service_uuids[17] = 0x18; // 高字节(注意小端模式?) 但是,注意:在广播数据中,16位的UUID是按照小端模式存储的,即先低字节后高字节。而心率服务的UUID是0x180D,所以在广播数据中应该存储为0x0D, 0x18。但是,我们上面构造的数组,第16字节是0x0D,第17字节是0x18,这是正确的。 然而,128位的UUID在广播数据中是如何存储的?配网服务的UUID是128位,在广播数据中按照原来的字节顺序(从高位到低位)存储。而我们在设置custom_service_uuid时,是按照从高位到低位(MSB first)存储的,所以直接拷贝即可。 但是,在广播数据中,128位的UUID应该按照从最低有效位到最高有效位(即小端模式)存储吗?实际上,在BLE规范中,UUID在广播数据中都是按照小端模式存储的。但是,配网服务的UUID在设置时(wifi_prov_scheme_ble_set_service_uuid)已经要求是MSB first(即大端模式),然后内部会转换为小端模式存储。所以,我们这里不能直接拷贝custom_service_uuid,因为custom_service_uuid是大端模式的,而广播数据需要小端模式。 这个问题比较复杂,我们最好不要直接操作UUID的字节序。我们可以让配网服务提供其广播数据中的UUID,但配网服务没有提供这样的接口。 因此,为了避免复杂性,我们采用扫描响应数据来包含自定义服务的UUID,而广播数据中只保留配网服务的UUID(由配网服务设置)。这样,手机在扫描设备时,会先收到广播数据(配网服务),然后发送扫描请求,设备回复扫描响应数据(包含自定义服务UUID)。这样手机就能同时发现两个服务。 具体步骤: 1. 在双模式下,启动配网服务(wifi_prov_mgr_start_provisioning)后,我们等待广播数据设置完成(ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT)。 2. 然后,我们设置扫描响应数据,其中包含自定义服务的UUID(16位)和 device name 等。 3. 在扫描响应数据设置完成后(ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT),我们开始广播(因为设置扫描响应数据时会停止广播)。 代码实现: static uint8_t adv_config_done = 0; #define ADV_CONFIG_FLAG (1 << 0) #define SCAN_RSP_CONFIG_FLAG (1 << 1) // 在gap_event_handler中: case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: if (current_bt_mode == BT_MODE_DUAL) { adv_config_done |= ADV_CONFIG_FLAG; if (adv_config_done == (ADV_CONFIG_FLAG | SCAN_RSP_CONFIG_FLAG)) { esp_ble_gap_start_advertising(&heart_rate_adv_params); } } break; case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: if (current_bt_mode == BT_MODE_DUAL) { adv_config_done |= SCAN_RSP_CONFIG_FLAG; if (adv_config_done == (ADV_CONFIG_FLAG | SCAN_RSP_CONFIG_FLAG)) { esp_ble_gap_start_advertising(&heart_rate_adv_params); } } break; 然后,在配网服务设置广播数据完成后(即收到ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT),我们设置扫描响应数据: case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: if (current_bt_mode == BT_MODE_DUAL) { // 配置扫描响应数据 uint8_t custom_service_uuid_16[2] = {0x0D, 0x18}; // 心率服务0x180D,小端存储 esp_ble_adv_data_t scan_rsp = { .set_scan_rsp = true, .include_name = true, .include_txpower = true, .min_interval = 0, .max_interval = 0, .appearance = 0, .manufacturer_len = sizeof(test_manufacturer), .p_manufacturer_data = test_manufacturer, .service_data_len = 0, .p_service_data = NULL, .service_uuid_len = sizeof(custom_service_uuid_16), .p_service_uuid = custom_service_uuid_16, .flag = 0, }; esp_ble_gap_config_adv_data(&scan_rsp); } break; 注意:这里我们只设置了扫描响应数据,然后在扫描响应数据设置完成事件中,我们开始广播(因为配网服务设置广播数据后已经开始广播了,但我们设置扫描响应数据时会停止广播,所以要重新开始)。 但是,配网服务设置的广播数据中只包含配网服务的UUID,扫描响应数据中包含了自定义服务的UUID。这样,手机扫描时就能发现两个服务。 4. 在双模式下,我们还需要注册自定义的GATT服务(心率服务)。这个服务在Dri_BT_Init()中已经注册了,所以只要蓝牙初始化了,就会存在。 5. 配网成功后的处理:配网成功后,我们会停止配网服务(wifi_prov_mgr_deinit),然后切换到仅GATT模式。在仅GATT模式下,我们只需要广播自定义服务(心率服务)即可。所以,在配网成功后,我们需要重新设置广播数据,只包含自定义服务的UUID。 6. 在配网成功的事件处理中(event_handler中WIFI_PROV_END事件),我们停止配网服务,然后设置仅GATT模式的广播数据,并开始广播。 具体代码: case WIFI_PROV_END: // 配置完成后,取消初始化管理器 wifi_prov_mgr_deinit(); // 切换到仅GATT模式 current_bt_mode = BT_MODE_GATT; // 停止当前的广播 esp_ble_gap_stop_advertising(); // 设置仅GATT模式的广播数据和扫描响应数据 // 这里我们使用自定义服务(心率服务)的广播数据 esp_ble_gap_config_adv_data(&heart_rate_adv_config); esp_ble_gap_config_adv_data(&heart_rate_scan_rsp_config); // 然后在设置完成后开始广播(在ADV和SCAN_RSP设置完成后开始广播,参考之前的代码) break; 但是,heart_rate_adv_config和heart_rate_scan_rsp_config是我们在Dri_BT.c中定义的,它们广播的是心率服务(0x180D)和制造商数据等。 注意:在双模式下,我们并没有使用heart_rate_adv_config和heart_rate_scan_rsp_config,而是使用了配网服务的广播数据和自定义的扫描响应数据。在切换到仅GATT模式后,我们重新设置广播数据为心率服务的广播数据。 7. 在双模式下,我们还需要注意:当有设备连接时,配网服务和自定义服务都能正常工作。但是,配网服务只处理它自己的特征值读写,自定义服务处理自己的特征值读写。 8. 在双模式下,如果设备通过配网服务连接,那么自定义服务可能无法同时连接?实际上,BLE协议允许一个从设备被多个主设备连接,但ESP32不支持。所以,同一时间只能有一个连接。配网服务和自定义服务共享同一个连接。因此,当手机连接后,既可以进行配网,也可以操作自定义服务。 但是,配网服务和自定义服务是两个独立的GATT服务,它们可以同时工作。手机APP可以同时访问这两个服务。 总结实现步骤: 1. 在未配网时,启动双模式(BT_MODE_DUAL): - 初始化蓝牙(Dri_BT_Init)-> 注册自定义GATT服务(心率服务)。 - 初始化配网服务(wifi_prov_mgr_init, wifi_prov_mgr_start_provisioning)-> 配网服务会设置广播数据(只包含配网服务的UUID)并开始广播。 - 在广播数据设置完成事件(ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT)中,设置扫描响应数据(包含自定义服务的UUID)。 - 在扫描响应数据设置完成事件(ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT)中,开始广播(此时广播数据包含配网服务UUID,扫描响应数据包含自定义服务UUID)。 2. 在配网成功后(WIFI_PROV_END事件): - 取消配网服务(wifi_prov_mgr_deinit)。 - 切换到仅GATT模式(current_bt_mode = BT_MODE_GATT)。 - 停止当前广播。 - 设置自定义服务的广播数据(heart_rate_adv_config)和扫描响应数据(heart_rate_scan_rsp_config)。 - 在广播数据和扫描响应数据设置完成后,开始广播。 3. 在已配网时,启动仅GATT模式(BT_MODE_GATT): - 直接广播自定义服务(heart_rate_adv_config和heart_rate_scan_rsp_config)。 代码修改: - 在Dri_Wifi.c中,我们已经在Dri_Wifi_Init函数中根据是否配网来设置current_bt_mode(未配网为BT_MODE_DUAL,已配网为BT_MODE_GATT)。 - 在Dri_BT.c中,我们需要修改gap_event_handler,以支持双模式下的扫描响应数据设置。 具体修改Dri_BT.c的gap_event_handler函数: static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) { switch (event) { case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: adv_config_done &= (~ADV_CONFIG_FLAG); if (adv_config_done == 0) { esp_ble_gap_start_advertising(&heart_rate_adv_params); } // 双模式:在配网服务设置广播数据完成后,设置扫描响应数据 if (current_bt_mode == BT_MODE_DUAL) { // 配置扫描响应数据 uint8_t custom_service_uuid_16[2] = {0x0D, 0x18}; // 0x180D in little endian esp_ble_adv_data_t scan_rsp = { .set_scan_rsp = true, .include_name = true, .include_txpower = true, .min_interval = 0, .max_interval = 0, .appearance = 0, .manufacturer_len = sizeof(test_manufacturer), .p_manufacturer_data = test_manufacturer, .service_data_len = 0, .p_service_data = NULL, .service_uuid_len = sizeof(custom_service_uuid_16), .p_service_uuid = custom_service_uuid_16, .flag = 0, }; esp_err_t ret = esp_ble_gap_config_adv_data(&scan_rsp); if (ret) { ESP_LOGE(GATTS_TABLE_TAG, "config scan response data failed, error code = %x", ret); } } break; case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: adv_config_done &= (~SCAN_RSP_CONFIG_FLAG); if (adv_config_done == 0) { esp_ble_gap_start_advertising(&heart_rate_adv_params); } break; // ... 其他事件 } } 但是,这里有一个问题:在双模式下,配网服务设置的广播数据完成后,我们设置扫描响应数据,这会触发ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT事件,然后在该事件中,我们会开始广播(因为adv_config_done被置为0)。但是,在双模式下,我们并不希望在这个时候开始广播,因为我们还没有设置扫描响应数据?实际上,我们在双模式下的扫描响应数据设置就是在配网服务设置广播数据完成后才触发的。 而且,在双模式下,我们设置扫描响应数据后,会触发ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT事件,然后在该事件中,adv_config_done会变成0(因为原来adv_config_done可能是ADV_CONFIG_FLAG,然后SCAN_RSP_CONFIG_FLAG被清除,所以0),然后开始广播。这样就会开始广播(包含配网服务的广播数据和自定义服务的扫描响应数据)。 所以,我们需要修改adv_config_done的用法,使其在双模式下也能正常工作。我们可以在双模式下,忽略adv_config_done的用法,而是直接开始广播。 或者,我们统一使用adv_config_done来管理,但是在双模式下,我们设置扫描响应数据时,会设置SCAN_RSP_CONFIG_FLAG,然后在扫描响应数据设置完成事件中,如果双模式,并且ADV_CONFIG_FLAG和SCAN_RSP_CONFIG_FLAG都设置好了,就开始广播。 修改: static uint8_t adv_config_done = 0; #define ADV_CONFIG_FLAG (1 << 0) #define SCAN_RSP_CONFIG_FLAG (1 << 1) case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: adv_config_done &= (~ADV_CONFIG_FLAG); if (current_bt_mode == BT_MODE_DUAL) { // 双模式下,设置扫描响应数据 ... // 同上 // 设置扫描响应数据后,我们将SCAN_RSP_CONFIG_FLAG置为0,表示正在设置 adv_config_done &= (~SCAN_RSP_CONFIG_FLAG); } else { if (adv_config_done == 0) { esp_ble_gap_start_advertising(&heart_rate_adv_params); } } break; case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: adv_config_done &= (~SCAN_RSP_CONFIG_FLAG); if (current_bt_mode == BT_MODE_DUAL) { // 双模式下,扫描响应数据设置完成,开始广播 if ((adv_config_done & ADV_CONFIG_FLAG) == 0 && (adv_config_done & SCAN_RSP_CONFIG_FLAG) == 0) { esp_ble_gap_start_advertising(&heart_rate_adv_params); } } else { if (adv_config_done == 0) { esp_ble_gap_start_advertising(&heart_rate_adv_params); } } break; 但是,双模式下,在广播数据设置完成事件中,我们设置扫描响应数据,然后扫描响应数据设置完成事件中,我们判断ADV_CONFIG_FLAG和SCAN_RSP_CONFIG_FLAG都被清除了(因为在设置扫描响应数据前,我们清除了SCAN_RSP_CONFIG_FLAG,而广播数据设置完成时清除了ADV_CONFIG_FLAG),所以条件成立,开始广播。 注意:adv_config_done的初始值是多少?在Dri_BT_Init中,我们并没有初始化adv_config_done,需要初始化为ADV_CONFIG_FLAG | SCAN_RSP_CONFIG_FLAG,表示都还没有设置。 所以,在Dri_BT_Init中,我们初始化: adv_config_done = ADV_CONFIG_FLAG | SCAN_RSP_CONFIG_FLAG; 这样,在双模式下,配网服务设置广播数据(ADV)完成后,我们清除ADV_CONFIG_FLAG,然后设置扫描响应数据(SCAN RSP),设置扫描响应数据会清除SCAN_RSP_CONFIG_FLAG(在事件中),然后当扫描响应数据设置完成时,两个标志都被清除,我们就开始广播。 而在非双模式下(仅GATT),我们设置广播数据和扫描响应数据,然后分别在设置完成事件中检查,当两个都完成时,开始广播。 但是,在双模式下,配网服务设置广播数据时,我们并没有设置adv_config_done,所以我们在双模式下的广播数据设置完成事件中,需要清除ADV_CONFIG_FLAG: case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: adv_config_done &= (~ADV_CONFIG_FLAG); ... // 双模式的处理 这样,双模式下,当配网服务设置广播数据完成,我们清除ADV_CONFIG_FLAG,然后设置扫描响应数据,扫描响应数据设置完成后,清除SCAN_RSP_CONFIG_FLAG,然后因为两个标志都被清除,所以开始广播。 因此,代码修改如下: static uint8_t adv_config_done = ADV_CONFIG_FLAG | SCAN_RSP_CONFIG_FLAG; static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) { switch (event) { case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: adv_config_done &= ~ADV_CONFIG_FLAG; // 清除ADV_CONFIG_FLAG if (current_bt_mode == BT_MODE_DUAL) { // 配置扫描响应数据 uint8_t custom_service_uuid_16[2] = {0x0D, 0x18}; // 0x180D in little endian esp_ble_adv_data_t scan_rsp = { .set_scan_rsp = true, .include_name = true, .include_txpower = true, .min_interval = 0, .max_interval = 0, .appearance = 0, .manufacturer_len = sizeof(test_manufacturer), .p_manufacturer_data = test_manufacturer, .service_data_len = 0, .p_service_data = NULL, .service_uuid_len = sizeof(custom_service_uuid_16), .p_service_uuid = custom_service_uuid_16, .flag = 0, }; esp_err_t ret = esp_ble_gap_config_adv_data(&scan_rsp); if (ret) { ESP_LOGE(GATTS_TABLE_TAG, "config scan response data failed, error code = %x", ret); } } else { // 非双模式,检查是否可以开始广播 if (adv_config_done == 0) { esp_ble_gap_start_advertising(&heart_rate_adv_params); } } break; case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: adv_config_done &= ~SCAN_RSP_CONFIG_FLAG; // 清除SCAN_RSP_CONFIG_FLAG if (current_bt_mode == BT_MODE_DUAL) { // 双模式,扫描响应数据设置完成,开始广播 if (adv_config_done == 0) { esp_ble_gap_start_advertising(&heart_rate_adv_params); } } else { if (adv_config_done == 0) { esp_ble_gap_start_advertising(&heart_rate_adv_params); } } break; // ... 其他事件 } } 9. 在配网成功后的切换(WIFI_PROV_END事件)中,我们切换到仅GATT模式,并重新设置广播数据: case WIFI_PROV_END: wifi_prov_mgr_deinit(); current_bt_mode = BT_MODE_GATT; // 切换到仅GATT模式 // 停止当前的广播 esp_ble_gap_stop_advertising(); // 设置新的广播数据(心率服务) adv_config_done = ADV_CONFIG_FLAG | SCAN_RSP_CONFIG_FLAG; // 重置标志 esp_ble_gap_config_adv_data(&heart_rate_adv_config); esp_ble_gap_config_adv_data(&heart_rate_scan_rsp_config); break; 10. 在仅GATT模式下,设置广播数据和扫描响应数据会触发对应的事件,然后在事件中,当两个都设置完成时,就会开始广播。 注意:heart_rate_adv_config和heart_rate_scan_rsp_config是我们在Dri_BT.c中定义的全局变量,它们分别是广播数据和扫描响应数据的配置。 这样,我们就实现了双模式和仅GATT模式的切换。 但是,还有一点:在双模式下,我们设置的扫描响应数据中的UUID是16位的自定义服务UUID(0x180D),而在仅GATT模式下,我们设置的广播数据heart_rate_adv_config中包含了16位的服务UUID(0x180D)和扫描响应数据heart_rate_scan_rsp_config中包含了制造商数据等。 因此,手机在双模式下扫描时,会看到: - 广播数据:配网服务UUID(128位) - 扫描响应数据:设备名称、自定义服务UUID(16位) 而在仅GATT模式下,会看到: - 广播数据:自定义服务UUID(16位)等 - 扫描响应数据:设备名称、制造商数据等 最后,我们还需要在Dri_Wifi.h中声明current_bt_mode,以便在Dri_BT.c中使用。但是,Dri_BT.c和Dri_Wifi.c都需要访问这个变量,所以我们可以在Dri_BT.h中声明为extern。 在Dri_BT.h中: extern bt_mode_t current_bt_mode; 在Dri_Wifi.c中,我们定义: bt_mode_t current_bt_mode = BT_MODE_DUAL; // 默认双模式 注意:在Dri_Wifi_Init中,已配网时我们会设置current_bt_mode = BT_MODE_GATT;。 由于代码量较大,以上是一个实现思路。由于篇幅限制,我不能提供完整的代码,但提供了关键部分的修改。 由于时间关系,以上方案可能还需要在实际中调试。但思路是可行的。 如果遇到问题,请根据实际调试情况调整。 注意:在双模式下,配网服务和自定义服务同时运行,可能会增加功耗,但这是临时的,配网完成后就会停止配网服务。 最后,在配网服务运行期间,如果有设备连接,那么设备名称会显示为配网服务的名称(我们在配网服务中设置的),而在仅GATT模式下,设备名称显示为"Zkevin_SmartHumidifier"(由esp_ble_gap_set_device_name设置)。 我们可以在Dri_BT_Init中设置设备名称: esp_ble_gap_set_device_name(example_device_name); 这个名称在双模式和仅GATT模式都会使用,所以扫描响应数据中的include_name=true会包含这个名称。 因此,在双模式下,扫描响应数据中会包含设备名称"Zkevin_SmartHumidifier"。 以上代码修改仅供参考,具体实现时需要根据实际情况调整。</think>要实现蓝牙的两种模式(配网模式和自定义GATT服务模式),关键在于管理BLE服务的注册和广播配置。以下是完整的实现方案,包含代码修改和解释: ### 1. 蓝牙模式管理实现 #### 修改头文件 `Dri_BT.h` ```c // 添加蓝牙模式枚举 typedef enum { BT_MODE_GATT, // 仅GATT服务模式 BT_MODE_DUAL // 双模式(配网+GATT) } bt_mode_t; // 声明全局模式变量 extern bt_mode_t current_bt_mode; // 添加双服务广播函数 void start_dual_service_advertising(void); ``` #### 修改 `Dri_BT.c` 实现 ```c // 在文件顶部添加 #include "wifi_provisioning/manager.h" #include "wifi_provisioning/scheme_ble.h" bt_mode_t current_bt_mode = BT_MODE_DUAL; // 默认双模式 // 修改广播参数 static esp_ble_adv_params_t heart_rate_adv_params = { .adv_int_min = 0x100, .adv_int_max = 0x100, .adv_type = ADV_TYPE_IND, .own_addr_type = BLE_ADDR_TYPE_RPA_PUBLIC, .channel_map = ADV_CHNL_ALL, .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY, }; // 新增函数:启动双服务广播 void start_dual_service_advertising(void) { // 1. 获取配网服务的UUID uint8_t *prov_uuid; uint8_t uuid_len; wifi_prov_scheme_ble_get_service_uuid(&prov_uuid, &uuid_len); // 2. 组合UUID列表(配网服务 + 自定义服务) uint8_t combined_uuids[16 + 2] = {0}; memcpy(combined_uuids, prov_uuid, 16); // 128位配网UUID combined_uuids[16] = 0x0D; // 心率服务UUID低字节 combined_uuids[17] = 0x18; // 心率服务UUID高字节 // 3. 配置广播数据 esp_ble_adv_data_t dual_adv_config = { .set_scan_rsp = false, .include_name = true, .include_txpower = true, .min_interval = 0x0006, .max_interval = 0x0010, .appearance = 0x00, .manufacturer_len = 0, .p_manufacturer_data = NULL, .service_data_len = 0, .p_service_data = NULL, .service_uuid_len = sizeof(combined_uuids), .p_service_uuid = combined_uuids, .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT), }; // 4. 更新扫描响应数据 esp_ble_adv_data_t dual_scan_rsp = { .set_scan_rsp = true, .include_name = true, .manufacturer_len = sizeof(test_manufacturer), .p_manufacturer_data = test_manufacturer, }; // 5. 应用新配置 esp_ble_gap_config_adv_data(&dual_adv_config); esp_ble_gap_config_adv_data(&dual_scan_rsp); esp_ble_gap_start_advertising(&heart_rate_adv_params); } // 修改GAP事件处理 static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) { switch (event) { case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: if (param->adv_start_cmpl.status != ESP_BT_STATUS_SUCCESS) { ESP_LOGE(GATTS_TABLE_TAG, "Advertising start failed: %x", param->adv_start_cmpl.status); } else if (current_bt_mode == BT_MODE_DUAL) { ESP_LOGI(GATTS_TABLE_TAG, "Dual-mode advertising active"); } break; // ... 其他事件处理保持不变 } } // 修改GATT事件处理 static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) { if (event == ESP_GATTS_REG_EVT) { // 仅当不是双模式时才设置设备名 if (current_bt_mode != BT_MODE_DUAL) { esp_ble_gap_set_device_name(example_device_name); } // ... 其他注册逻辑 } } ``` #### 修改 `Dri_Wifi.c` 实现 ```c // 在事件处理函数中 static void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { if (event_base == WIFI_PROV_EVENT) { switch (event_id) { case WIFI_PROV_START: ESP_LOGI(TAG, "Provisioning started"); // 双模式:启动双服务广播 if (current_bt_mode == BT_MODE_DUAL) { start_dual_service_advertising(); } break; case WIFI_PROV_END: // 配网完成后切换为仅GATT模式 current_bt_mode = BT_MODE_GATT; esp_ble_gap_stop_advertising(); esp_ble_gap_start_advertising(&heart_rate_adv_params); break; // ... 其他事件 } } } void Dri_Wifi_Init(wifi_conn wifi_conn_success) { // ... 初始化代码不变 // 检查配网状态 bool provisioned = false; ESP_ERROR_CHECK(wifi_prov_mgr_is_provisioned(&provisioned)); if (!provisioned) { current_bt_mode = BT_MODE_DUAL; // 未配网时使用双模式 // ... 配网初始化 } else { current_bt_mode = BT_MODE_GATT; // 已配网使用GATT模式 // ... 直接启动WiFi } } ``` ### 2. 关键实现解释 1. **双模式实现原理**: - 在未配网状态时,设备同时广播配网服务UUID(128位)和自定义GATT服务UUID(16位心率服务) - 使用`combined_uuids`数组组合两个服务的UUID - 广播数据包含完整的服务列表,使手机能同时发现两个服务 2. **模式切换机制**: - 初始状态:`BT_MODE_DUAL`(未配网) - 配网成功后:切换为`BT_MODE_GATT` - 在`WIFI_PROV_END`事件中更新广播配置 3. **广播管理**: - `start_dual_service_advertising()`:构建组合UUID并配置广播 - 配网完成后重新启动单服务广播 - 使用`esp_ble_gap_stop_advertising()`确保广播平滑切换 4. **服务共存**: - 配网服务使用`wifi_prov_mgr`组件管理 - 自定义GATT服务独立注册 - 蓝牙协议栈自动处理多服务请求分发 ### 3. 工作流程示例 ```mermaid graph TD A[设备启动] --> B{已配网?} B -->|否| C[双模式启动] C --> D[注册配网服务] C --> E[注册GATT服务] C --> F[广播双服务UUID] B -->|是| G[仅GATT模式] G --> H[广播GATT服务] G --> I[启动WiFi连接] D --> J[配网成功] J --> K[切换GATT模式] K --> L[停止配网服务] K --> M[更新广播配置] ``` ### 4. 常见问题处理 1. **服务冲突**: - 确保两个服务使用不同的特征UUID - 在GATT事件处理中根据服务ID分发请求 2. **广播数据超限**: - BLE广播限制31字节 - 使用`esp_ble_adv_data_t`的`service_uuid_len`确保不超限 - 必要时牺牲部分制造商数据 3. **连接稳定性**: - 配网时设置`heart_rate_adv_params.adv_int_min`增加广播间隔 - 使用`ESP_BLE_ADV_FLAG_BREDR_NOT_SPT`优化BLE-only设备 ### 5. 测试建议 1. **双模式验证**: - 使用nRF Connect扫描应显示两个服务 - 配网服务UUID:自定义128位UUID - GATT服务UUID:0x180D(心率) 2. **模式切换测试**: - 配网成功后确认广播数据更新 - 验证配网服务不可用 - 确认GATT服务保持正常 3. **边界测试**: - 配网过程中GATT服务读写 - 快速切换模式下的稳定性 - 低功耗模式下的广播行为 ### 6. 优化方向 1. **动态广播配置**: ```c void update_adv_data_based_on_mode() { if (current_bt_mode == BT_MODE_DUAL) { // 双模式配置 } else { // 单模式配置 } } ``` 2. **连接优先级管理**: ```c // 在连接事件中 case ESP_GATTS_CONNECT_EVT: if (current_bt_mode == BT_MODE_DUAL) { // 提升配网服务优先级 } ``` 3. **功耗优化**: - 双模式使用更长的广播间隔 - 配网成功后立即降低广播频率 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值