Skip to content

Instantly share code, notes, and snippets.

@srgtuszy
Created October 26, 2017 14:26
Show Gist options
  • Save srgtuszy/25b11add2d6f9ef3729f682f849ede40 to your computer and use it in GitHub Desktop.
Save srgtuszy/25b11add2d6f9ef3729f682f849ede40 to your computer and use it in GitHub Desktop.
BLE Peripheral
var bleno = require('bleno');
bleno.on('stateChange', function(state) {
console.log('State change: ' + state);
if (state === 'poweredOn') {
console.log('advertising')
bleno.startAdvertising('MyPeripheral',['12ab']);
} else {
bleno.stopAdvertising();
}
});
bleno.on('accept', function(clientAddress) {
console.log("Accepted connection from address: " + clientAddress);
});
bleno.on('disconnect', function(clientAddress) {
console.log("Disconnected from address: " + clientAddress);
});
bleno.on('advertisingStart', function(error) {
if (error) {
console.log("Advertising start error:" + error);
} else {
console.log("Advertising start success");
bleno.setServices([
new bleno.PrimaryService({
uuid : '12ab',
characteristics : [
new bleno.Characteristic({
value : null,
uuid : '34cd',
properties : ['notify', 'read', 'write'],
// If the client subscribes, we send out a message every 1 second
onSubscribe : function(maxValueSize, updateValueCallback) {
console.log("Device subscribed");
this.intervalId = setInterval(function() {
console.log("Sending: Hi!");
updateValueCallback(new Buffer("Hi!"));
}, 1000);
},
// If the client unsubscribes, we stop broadcasting the message
onUnsubscribe : function() {
console.log("Device unsubscribed");
clearInterval(this.intervalId);
},
// Send a message back to the client with the characteristic's value
onReadRequest : function(offset, callback) {
console.log("Read request received");
callback(this.RESULT_SUCCESS, new Buffer("Echo: " +
(this.value ? this.value.toString("utf-8") : "")));
},
// Accept a new value for the characterstic's value
onWriteRequest : function(data, offset, withoutResponse, callback) {
this.value = data;
console.log('Write request: value = ' + this.value.toString("utf-8"));
callback(this.RESULT_SUCCESS);
}
})
]
})
]);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment