Skip to content

Instantly share code, notes, and snippets.

@don
Created January 16, 2018 02:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save don/ad3d6f444925c57d169baf54e262348f to your computer and use it in GitHub Desktop.
Save don/ad3d6f444925c57d169baf54e262348f to your computer and use it in GitHub Desktop.
Break up large ArrayBuffer before writing to BLE characteristic
// 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);
@mrameen
Copy link

mrameen commented Nov 9, 2020

THANK YOU. BLE LIMIT 20 SUCCESS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment