蓝牙配网协议
850字约3分钟
2025-9-9
小程序蓝牙连接设备案列
uni.createBLEConnection({
deviceId: "扫描到的设备ID",
timeout: 10000, // 10秒超时
success: (res) => {
console.log('连接成功:', res);
data.deviceId = arr[0].deviceId;
getDeviceServices(arr[0].deviceId);
},
fail: (err) => {
console.error('连接失败:', err);
}
});
// 获取设备服务
const getDeviceServices = (deviceId) => {
uni.getBLEDeviceServices({
deviceId,
success: (res) => {
console.log('设备服务:', res.services);
// 获取主服务(根据设备协议选择正确的服务UUID)
data.deviceServer = res.services[0].uuid; // 示例:选择第一个服务
// 获取服务特征
getDeviceCharacteristics(deviceId, res.services[0].uuid);
},
fail: (err) => {
console.error('获取服务失败:', err);
}
});
};
// 获取设备特征
const getDeviceCharacteristics = (deviceId, serviceId) => {
uni.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res) => {
console.log('设备特征:', res.characteristics[0].uuid);
},
fail: (err) => {
console.error('获取特征失败:', err);
},
complete: () => {
uni.hideLoading()
}
});
};
小程序蓝牙发送案列代码
const EOT_MARKER = "--END--";
async function sendBleDataFunction({
// 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId,
// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId,
data,
onEnd
}) {
const reqData = str2ab(encodeURIComponent(JSON.stringify(data)));
// console.log('deviceId:', deviceId);
// console.log('serviceId:', serviceId);
// console.log('characteristicId:', characteristicId);
// console.log('Total data to send (ArrayBuffer):', reqData);
// console.log('Total data byteLength:', reqData.byteLength);
const chunkSize = 32;
try {
const success = await sendDataInChunks(
deviceId,
serviceId,
characteristicId,
reqData,
chunkSize // 使用计算出的分包大小
);
if (success) {
console.log('所有数据包均已成功发送!');
try {
await new Promise((resolve, reject) => {
uni.writeBLECharacteristicValue({
deviceId,
serviceId,
characteristicId,
value: str2ab(EOT_MARKER), // EOT_MARKER 必须和 ESP32 端定义的一致,例如 "--END--"
success(res) {
console.log('结束标记发送成功:', res.errMsg);
resolve(res);
},
fail(err) {
console.error('结束标记发送失败:', err);
reject(err);
}
});
});
console.log('所有操作完成,包括结束标记。');
onEnd && onEnd();
} catch (eotError) {
console.error('发送结束标记时出错:', eotError);
uni.showToast({ title: '完成信号发送失败', icon: 'none' });
}
} else {
console.log('数据发送过程中发生错误。');
// 可以在这里给用户提示
uni.showToast({ title: '数据发送失败', icon: 'none' });
}
} catch (error) {
console.log('写入过程中出现异常:', error);
uni.showToast({ title: '写入异常', icon: 'none' });
} finally {
// data.saveLoading = false;
}
}
/**
* 将 ArrayBuffer 数据分块并通过 BLE 发送
* @param {string} deviceId - 蓝牙设备 ID
* @param {string} serviceId - 服务 ID
* @param {string} characteristicId - 特征 ID
* @param {ArrayBuffer} buffer - 需要发送的完整数据 ArrayBuffer
* @param {number} chunkSize - 每个数据块的最大字节数 (例如: peer_MTU - 3)
* @returns {Promise<boolean>} - 发送成功返回 true, 失败返回 false
*/
async function sendDataInChunks(deviceId, serviceId, characteristicId, buffer, chunkSize) {
console.log(`Preparing to send ${buffer.byteLength} bytes in chunks of ${chunkSize} bytes.`);
let offset = 0;
while (offset < buffer.byteLength) {
const chunk = buffer.slice(offset, Math.min(offset + chunkSize, buffer.byteLength));
offset += chunk.byteLength;
console.log(`Sending chunk of ${chunk.byteLength} bytes. Remaining: ${buffer.byteLength - offset}`);
try {
await new Promise((resolve, reject) => {
uni.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: characteristicId,
value: chunk,
success(res) {
console.log('Chunk sent successfully:', res.errMsg);
// 可以在这里加一个短暂的延时,给蓝牙协议栈一些处理时间
setTimeout(resolve, 50); // 例如 50ms
// resolve(res);
},
fail(err) {
console.error('Chunk send failed:', err);
reject(err); // 如果一个分片失败,则停止发送
}
});
});
} catch (error) {
console.error('Error during chunk sending, aborting.', error);
return false; // 表示发送失败
}
}
console.log('All chunks sent successfully.');
return true; // 表示所有分片发送成功
}
// 在具体的调用下面函数
// 下面具体的数据
let obj = {
wifi_name: "wifi 名称",
wifi_pwd: "wifi 密码",
ext1: "超体 api_key"
ext7: "唤醒方式",
// kwh_enable: data.isSwitchKwh ? '1' : '0',
// volume_enable: data.isSwitchVol ? '1' : '0',
// volume_pin: data.volVal,
// lights_data: data.pinVal,
// oled_type: '096',
// oled_sck: data.oled_sck,
// oled_sda: data.oled_sda,
// mic_bck: data.mic_bck,
// mic_ws: data.mic_ws,
// mic_data: data.mic_data,
// speaker_bck: data.speaker_bck,
// speaker_ws: data.speaker_ws,
// speaker_data: data.speaker_data,
}
sendBleDataFunction({
// 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId: "xxx",
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId:"xxx",
// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId: "xxx",
data: obj,
onEnd() {
data.saveLoading = false
back()
}
});