美文网首页
微信小程序 从服务中获取 bin文件 , 进行切片,然后发送到

微信小程序 从服务中获取 bin文件 , 进行切片,然后发送到

作者: 小李不小 | 来源:发表于2024-09-03 19:11 被阅读0次

步骤

1,从服务器获取 .bin 文件:使用 wx.request 方法从服务器下载文件。
2,将文件内容切片:将获取的文件内容切割成多个小块。
3,连接到蓝牙设备:确保已连接到目标蓝牙设备。
4,循环发送数据块:使用 wx.writeBLECharacteristicValue 方法将每个数据块发送到蓝牙设备。

// 切割文件的函数  
function splitFile(arrayBuffer, chunkSize) {  
    const chunks = [];  
    let offset = 0;  

    while (offset < arrayBuffer.byteLength) {  
        const chunk = arrayBuffer.slice(offset, offset + chunkSize);  
        chunks.push(chunk);  
        offset += chunkSize;  
    }  

    return chunks;  
}  

// 从服务器获取 .bin 文件  
function fetchBinFile(url, deviceId, serviceId, characteristicId) {  
    wx.request({  
        url: url,  
        method: 'GET',  
        responseType: 'arraybuffer', // 设置响应类型为 arraybuffer  
        success: function (res) {  
            if (res.statusCode === 200) {  
                const arrayBuffer = res.data; // 获取文件内容  
                const chunkSize = 20; // 设置每个块的大小(例如:20字节)  
                const chunks = splitFile(arrayBuffer, chunkSize);  
                sendChunksToBluetooth(deviceId, serviceId, characteristicId, chunks);  
            } else {  
                console.error('获取文件失败', res);  
            }  
        },  
        fail: function (err) {  
            console.error('请求失败', err);  
        }  
    });  
}  

// 循环发送数据块到蓝牙设备  
function sendChunksToBluetooth(deviceId, serviceId, characteristicId, chunks) {  
    let index = 0;  

    function sendNextChunk() {  
        if (index < chunks.length) {  
            wx.writeBLECharacteristicValue({  
                deviceId: deviceId,  
                serviceId: serviceId,  
                characteristicId: characteristicId,  
                value: chunks[index], // 传递当前块  
                success: function (res) {  
                    console.log(`块 ${index + 1} 发送成功`, res);  
                    index++;  
                    sendNextChunk(); // 发送下一个块  
                },  
                fail: function (err) {  
                    console.error(`块 ${index + 1} 发送失败`, err);  
                }  
            });  
        } else {  
            console.log('所有数据块已发送');  
        }  
    }  

    sendNextChunk(); // 开始发送第一个块  
}  

// 示例调用  
const url = 'https://example.com/path/to/your/file.bin'; // 替换为你的文件 URL  
const deviceId = 'your-device-id'; // 替换为你的设备 ID  
const serviceId = 'your-service-id'; // 替换为你的服务 ID  
const characteristicId = 'your-characteristic-id'; // 替换为你的特征 ID  

// 从服务器获取文件并发送到蓝牙  
fetchBinFile(url, deviceId, serviceId, characteristicId);

1,切割文件:splitFile 函数将 ArrayBuffer 切割成指定大小的块,并返回一个包含所有块的数组。

2,获取文件:使用 wx.request 方法从服务器获取 .bin 文件,设置 responseType 为 arraybuffer 以获取二进制数据。

3,发送数据块:sendChunksToBluetooth 函数循环发送每个数据块到蓝牙设备。使用递归调用 sendNextChunk 方法,确保每个块在前一个块成功发送后发送。

相关文章

网友评论

      本文标题:微信小程序 从服务中获取 bin文件 , 进行切片,然后发送到

      本文链接:https://www.haomeiwen.com/subject/yjtlljtx.html