noble / bleno

A Node.js module for implementing BLE (Bluetooth Low Energy) peripherals
MIT License
2.12k stars 447 forks source link

Sending Files? #384

Open javanese84 opened 6 years ago

javanese84 commented 6 years ago

Hey there,

I'm really new to bluetooth, but I wanted to ask, if I'm on the correct way for sending a picture-file over bleno to a Ionic App via Bluetooth. Up to now I have the following code:

var DynamicReadOnlyCharacteristic = function() {
  DynamicReadOnlyCharacteristic.super_.call(this, {
    uuid: 'fffffffffffffffffffffffffffffff2',
    properties: ['read']
  });
};

util.inherits(DynamicReadOnlyCharacteristic, BlenoCharacteristic);

DynamicReadOnlyCharacteristic.prototype.onReadRequest = function(offset, callback) {
  var result = this.RESULT_SUCCESS;
  console.log('sending image');
  var data = new Buffer(base64_encode('picture.jpg'));

  if (offset > data.length) {
    result = this.RESULT_INVALID_OFFSET;
    data = null;
  } else {
    data = data.slice(offset);
  }
  callback(result, data);
};

On my Ionic side I'm just trying to decode my base64 string but without success. Am I on the right way or is there a general misunderstanding on my side?

Thanks!

don commented 6 years ago

Generally sending files like images over BLE is going to be slow and painful. I don't recommend it.

You shouldn't need to base64 encode the file. When you read a file, you get the contents in a Buffer. var buffer = fs.readFileSync('picture.jpg') Characteristics are just bytes so you can write the buffer to the characteristic. When your app reads the characteristic, write the bytes to a new file.

The problem is that the size of your buffer likely exceeds the max characteristic size of 500 bytes. (Bluetooth 5 increases this to 2000 bytes. Many older peripherals have a max of 20 bytes.) In any case, you need to break the file into chunks and re-assemble the chunks on the other side.

Since all your data won't fit in one characteristic, you probably want that characteristic to be NOTIFY instead of READ. Have the client subscribe to the characteristic. Then in bleno, you can write chunks of data to the characteristic and it will get sent to the client. Here's a old project that slowly sent log files over BLE that might give you some ideas how to implement https://github.com/don/rfduino-logreader.