主机发送信息使用的是:bStatus_t GATT_WriteCharValue( uint16 connHandle, attWriteReq_t *pReq, uint8 taskId );
一共三个参数:
connHandle - connection to use
pReq - pointer to request to be sent
taskId - task to be notified of response
第一个参数是与之连接特征值的handle ,看做地址即可。 在centeral 工程里 是在simpleBLEGATTDiscoveryEvent函数中的.simpleBLECharHdl = BUILD_UINT16( pMsg->msg.readByTypeRsp.dataList[0], pMsg->msg.readByTypeRsp.dataList[1] );获取的。
第二个参数就是要发送的数据
第三个数据就是当前任务的ID: 定义在全局变量 static uint8 simpleBLETaskId;
在初始化函数SimpleBLECentral_Init()中进行赋值simpleBLETaskId = task_id;
这就有一个小问题,假如从机有多个特征值 (例如simpleBLEperipheral工程中有五个特征值),那么主机是如何获得从机里指定的特征值的handle的,仔细看源码是在simpleBLEGATTDiscoveryEvent中
simpleBLEDiscState = BLE_DISC_STATE_CHAR; req.startHandle = simpleBLESvcStartHdl; req.endHandle = simpleBLESvcEndHdl; req.type.len = ATT_BT_UUID_SIZE; req.type.uuid[0] = LO_UINT16(SIMPLEPROFILE_CHAR1_UUID); req.type.uuid[1] = HI_UINT16(SIMPLEPROFILE_CHAR1_UUID); GATT_ReadUsingCharUUID( simpleBLEConnHandle, &req, simpleBLETaskId );如果想改变读取其他的特征值的 handle 的话 将 SIMPLEPROFILE_CHAR1_UUID 改变一下就可以了。注意读写特征值需要在从机 profile 中做出相应的属性设置。 下面是可以正常发送数据的例子:
uint8 sbpGattWriteString(uint8 *pBuffer, uint16 length) { uint8 len; if(length > 20) len = 20; else len = length; attWriteReq_t req; req.handle = simpleBLECharHdl; req.len = len; req.sig = 0; req.cmd = 0; osal_memcpy(req.value,pBuffer,len); return (GATT_WriteCharValue( simpleBLEConnHandle, &req, simpleBLETaskId )); }
主机接收从机发来的数据
两种方法:
第一种:主机使用GATT_ReadCharValue函数进行数据的接收, bStatus_t GATT_ReadCharValue( uint16 connHandle, attReadReq_t *pReq, uint8 taskId );
同样也有三个参数
connHandle - connection to use
pReq - pointer to request to be sent
taskId - task to be notified of response
第二种:直接采用通知的方法监听数据
由于主机采用这种方式接收数据的时候,不许要进行发送确认信息,所以适合较大数量的发送,但最大也就是20字节。数据到达主机后,BLE就把当前来的数据打包成一个OSAL massage,通知GATT层返回给了应用程序,这时候ATT_HANDLE_VALUE_NOTI || ATT_HANDLE_VALUE_IND 相应的被置位。在消息处理函数中就可以接收到当前从机发来的数据了。
if ( pMsg->method == ATT_HANDLE_VALUE_NOTI || pMsg->method == ATT_HANDLE_VALUE_IND ) { attHandleValueNoti_t noti; noti.handle = pMsg->msg.handleValueNoti.handle; noti.len = pMsg->msg.handleValueNoti.len; osal_memcpy(¬i.value, &pMsg->msg.handleValueNoti.value,noti.len); Uart0Send_String(noti.value,noti.len);// 串口打印数据 }