Skip to content

Commit

Permalink
Adding connect, read and write
Browse files Browse the repository at this point in the history
  • Loading branch information
yining1023 committed Dec 26, 2018
1 parent 3830963 commit 233db34
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.DS_Store
node_modules
23 changes: 23 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "p5.ble",
"version": "0.0.1",
"description": "A p5.js library that enables communication between BLE devices and a p5 sketch.",
"main": "src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/yining1023/p5.ble.js.git"
},
"keywords": [
"p5js",
"ble"
],
"author": "Yining Shi <[email protected]> (https://1023.io/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/yining1023/p5.ble.js/issues"
},
"homepage": "https://github.com/yining1023/p5.ble.js#readme"
}
48 changes: 48 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
const connect = (serviceUuid, callback) => {
const options = {
filters: [{
services: [serviceUuid]
}]
};

console.log('Requesting Bluetooth Device...');

return navigator.bluetooth.requestDevice(options)
.then(device => {
console.log(`Got device ${device.name}`);
return device.gatt.connect();
})
.then(server => {
console.log('Getting Service...');
return server.getPrimaryService(serviceUuid);
})
.then(service => {
console.log('Getting Characteristics...');
return service.getCharacteristics();
})
.then(characteristics => {
console.log('Got Characteristic');
callback(null, characteristics);
})
.catch(error => {
console.log(`Error: ${error}`);
callback(error);
});
}

const read = async (characteristic, callback) => {
const value = await characteristic.readValue();
return callback(null, value.getUint8(0));
}

const write = (characteristic, inputValue) => {
let bufferToSend = Uint8Array.of(inputValue);
characteristic.writeValue(bufferToSend);
console.log(`Writing ${inputValue} to Characteristic...`);
}

module.exports = {
connect,
read,
write
}

0 comments on commit 233db34

Please sign in to comment.