How do I send and receive series of data Bytes between a bluetooth device and Android/iOS in Cordova?
The details of my project:
I have a bluetooth sensor device that I am developing. The device sends data as a series of bytes. It also uses a binary control word system for the device API and sends/receives commands as series of bytes. So I need to receive and send unsigned bytes (8-bit values, 0-255). This setup was easy use in Java and Arduino. I have working computer and arduino apps communicating with the device using a simple serial connection.
Now I am developing a mobile app using Cordova, Angular, Ionic, and the bluetoothSerial plugin (excellent work by Don Coleman)github here. The app must run on android and iOS.
UPDATE: More Details, and The Answer: Sanfor pointed out that bluetoothSerial has a write() method that takes Uint8Array. Perhaps I am doing something wrong, but I cannot get this method to work! Here is what I tried:
var buf = new ArrayBuffer(2);
var view = new Uint8Array(buf);
view[0] = 0;
view[1] = 200;
//write(view); // does not work either
// re: 123,101,100,123,34,101,149,189,201,137,149,189,201,149,153,149,101,149,189,201,255
//write(buf); // does not work
// re: 65,97,77,101,115,77,103,101,115,103,61,101,115,61
writeBuffer(buf); // does work - thanks to Glen Arrowsmith!
// correct response: 0,101,100,0,200,101,100,200
Also, attempts to use bluetoothSerial.read could be forced to work for 7-bit numbers. There are variations using Uint8Arrays, but they just change how the data receipt fails because the inBuffer is converted to String inside bluetoothSerial. :
bluetoothSerial.read(readSuccess, simpleLog); // does not work
function readSuccess ( data ) {
var arr = [];
for (var i=0; i<data.length;i++){
arr.push(data.charCodeAt(i));
} // returned data is corrupted for all values over 127!
console.log('Converted ' + arr3 + ' with length ' + arr3.length);
}
THE ANSWER:
I found Glen Arrowsmith's fork of bluetoothSerial github with added readBuffer and writeBuffer (works in the code above). However, I've noticed that writeBuffer(buf) doesn't work properly for arrays longer than 2-3 elements! Is this a timing issue? It's possible it's on the device side. For now I've got an $interval setup to send out bytes of a larger array working.
I was also able to get reading working, though only after some work (the cast to Uint8Array) to get the Bytes back out in proper form:
bluetoothSerial.readBuffer(readSuccess, simpleLog);
function readSuccess ( data ) {
var arr = new Uint8Array(data);
var msg = '';
for (var i = 0; i < arr.length; i++){
msg += arr[i]+', ';
}
console.log('Received ' +arr+' with vals '+msg+'and length '+arr.length);
cb(arr);
}
UPDATE 2: I seem to have answered my own question by finding a forked version of bluetoothSerial and then adding in the above modifications to the output. I'll update if anybody suggests a cleaner method.