Created
January 16, 2018 02:08
-
-
Save don/ad3d6f444925c57d169baf54e262348f to your computer and use it in GitHub Desktop.
Break up large ArrayBuffer before writing to BLE characteristic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Mock BLE so you can run example from nodejs | |
const ble = { | |
write: function(device_id, service, characteristic, buffer, success, failure) { | |
// log to console instead of writing | |
console.log('>>', new Uint8Array(buffer)); | |
// always call success callback | |
success(); | |
} | |
} | |
// fake device and service | |
const device_id = 'aa:bb:cc:dd:ee:ff'; | |
const service_uuid = 'AAA0'; | |
const characteristic_uuid = 'AAA1'; | |
const MAX_DATA_SEND_SIZE = 20; | |
// write large ArrayBuffer by breaking into smaller chunks | |
function writeLargeData(buffer) { | |
console.log('writeLargeData', buffer.byteLength, 'bytes in',MAX_DATA_SEND_SIZE, 'byte chunks.'); | |
var chunkCount = Math.ceil(buffer.byteLength / MAX_DATA_SEND_SIZE); | |
var chunkTotal = chunkCount; | |
var index = 0; | |
var startTime = new Date(); | |
var transferComplete = function () { | |
console.log("Transfer Complete"); | |
} | |
var sendChunk = function () { | |
if (!chunkCount) { | |
transferComplete(); | |
return; // so we don't send an empty buffer | |
} | |
console.log('Sending data chunk', chunkCount + '.'); | |
var chunk = buffer.slice(index, index + MAX_DATA_SEND_SIZE); | |
index += MAX_DATA_SEND_SIZE; | |
chunkCount--; | |
ble.write( | |
device_id, | |
service_uuid, | |
characteristic_uuid, | |
chunk, | |
sendChunk, // success callback - call sendChunk() (recursive) | |
function(reason) { // error callback | |
console.log('Write failed ' + reason); | |
} | |
) | |
} | |
// send the first chunk | |
sendChunk(); | |
} | |
// Generate some fake data | |
const data = new Uint8Array(50); | |
for (let i = 0; i < 50; i++){ | |
data[i] = i; | |
} | |
writeLargeData(data.buffer); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
THANK YOU. BLE LIMIT 20 SUCCESS