微信小程序 從服務中獲取 bin文件 , 進行切片,然后發送到藍牙中

步驟

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 方法,確保每個塊在前一個塊成功發送后發送。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。