BluetoothGatt中的writeCharacteristic的实现在GattService中,如下:
void writeCharacteristic(int clientIf, String address, int handle, int writeType, int authReq, byte[] value) {
gattClientWriteCharacteristicNative(connId, handle, writeType, authReq, value);
}
这个gattClientWriteCharacteristicNative的实现在com_android_bluetooth_gatt.cpp中,
static void gattClientWriteCharacteristicNative(JNIEnv* env, jobject object,
jint conn_id, jint handle, jint write_type, jint auth_req, jbyteArray value) {
......
sGattIf->client->write_characteristic(conn_id, handle, write_type, auth_req,
std::move(vect_val));
}
这个sGattIf的client是定义在btif_gatt_client.c中的btgattClientInterface,这里调到了btif_gattc_write_char函数,
static bt_status_t btif_gattc_write_char(int conn_id, btgatt_srvc_id_t* srvc_id,
btgatt_gatt_id_t* char_id, int write_type,
int len, int auth_req, char* p_value)
{
btif_gattc_cb_t btif_cb;
btif_cb.conn_id = (uint16_t) conn_id;
btif_cb.auth_req = (uint8_t) auth_req;
btif_cb.write_type = (uint8_t) write_type;
btif_cb.len = len > BTGATT_MAX_ATTR_LEN ? BTGATT_MAX_ATTR_LEN : len;
memcpy(&btif_cb.srvc_id, srvc_id, sizeof(btgatt_srvc_id_t));
memcpy(&btif_cb.char_id, char_id, sizeof(btgatt_gatt_id_t));
memcpy(btif_cb.value, p_value, btif_cb.len);
return btif_transfer_context(btgattc_handle_event, BTIF_GATTC_WRITE_CHAR,
(char*) &btif_cb, sizeof(btif_gattc_cb_t), NULL);
}
这里发送到btif task中,由btgattc_handle_event处理,事件为BTIF_GATTC_WRITE_CHAR,如下:
case BTIF_GATTC_WRITE_CHAR:
btif_to_bta_srvc_id(&in_char_id.srvc_id, &p_cb->srvc_id);
btif_to_bta_gatt_id(&in_char_id.char_id, &p_cb->char_id);
BTA_GATTC_WriteCharValue(p_cb->conn_id, &in_char_id,
p_cb->write_type,
p_cb->len,
p_cb->value,
p_cb->auth_req);
break;
再来看看BTA_GATTC_WriteCharValue的实现,如下:
void BTA_GATTC_WriteCharValue ( UINT16 conn_id,
tBTA_GATTC_CHAR_ID *p_char_id,
tBTA_GATTC_WRITE_TYPE write_type,
UINT16 len,
UINT8 *p_value,
tBTA_GATT_AUTH_REQ auth_req)
{
tBTA_GATTC_API_WRITE *p_buf;
if ((p_buf = (tBTA_GATTC_API_WRITE *) GKI_getbuf((UINT16)(sizeof(tBTA_GATTC_API_WRITE) + len))) != NULL)
{
memset(p_buf, 0, sizeof(tBTA_GATTC_API_WRITE) + len);
p_buf->hdr.event = BTA_GATTC_API_WRITE_EVT;
p_buf->hdr.layer_specific = conn_id;
p_buf->auth_req = auth_req;
memcpy(&p_buf->srvc_id, &p_char_id->srvc_id, sizeof(tBTA_GATT_SRVC_ID));
memcpy(&p_buf->char_id, &p_char_id->char_id, sizeof(tBTA_GATT_ID));
p_buf->write_type = write_type;
p_buf->len = len;
if (p_value && len > 0)
{
p_buf->p_value = (UINT8 *)(p_buf + 1);
memcpy(p_buf->p_value, p_value, len);
}
bta_sys_sendmsg(p_buf);
}
return;
}
这里看来真正的写是在btu_task中,这里发送的事件为BTA_GATTC_API_WRITE_EVT。如下:
enum
{
BTA_GATTC_API_OPEN_EVT = BTA_SYS_EVT_START(BTA_ID_GATTC),
BTA_GATTC_INT_OPEN_FAIL_EVT,
BTA_GATTC_API_CANCEL_OPEN_EVT,
BTA_GATTC_INT_CANCEL_OPEN_OK_EVT,
BTA_GATTC_API_READ_EVT,
BTA_GATTC_API_WRITE_EVT,
......
};
可见这些事件都属于BTA_ID_GATTC的子系统,所以在btu_task中的事件处理函数为bta_gattc_main.c中的bta_gattc_hdl_event。奇怪的是在这个函数中没找到这个事件的处理分支,而是走到了默认处理逻辑中,如下:
tBTA_GATTC_CLCB *p_clcb = bt