Created
January 24, 2020 22:31
-
-
Save doojinkang/f825bf4f8f1883802d15bbfec2bf4173 to your computer and use it in GitHub Desktop.
BLE Arduino Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var noble = require('@abandonware/noble'); | |
var deviceInfoUUID = '180a'; | |
var bleServiceUUID = process.argv[2].toLowerCase(); // 'dfb0' or 'ffe0'; | |
var serialPortCharacteristicUUID = process.argv[3].toLowerCase(); // 'dfb1', or 'ffe1'; | |
var serialPortCharacteristic = null; | |
var found = false; | |
noble.on('stateChange', function(state) { | |
if (state === 'poweredOn') { | |
noble.startScanning(); | |
} else { | |
noble.stopScanning(); | |
} | |
}); | |
noble.on('discover', function(peripheral) { | |
peripheral.connect(function(error) { | |
console.log('connected to peripheral: ' + peripheral.uuid); | |
peripheral.discoverServices([deviceInfoUUID, bleServiceUUID], function(error, services) { | |
console.log('discovered the following services: ' + services.length); | |
for (var serviceIndex in services) { | |
var service = services[serviceIndex]; | |
console.log('- ' + serviceIndex + ' uuid: ' + service.uuid); | |
serialPortCharacteristic = null; | |
service.discoverCharacteristics([], function(error, characteristics) { | |
console.log(' + characteristics : ' + characteristics.length); | |
for (var characteristicIndex in characteristics) { | |
var characteristic = characteristics[characteristicIndex]; | |
console.log(' ' + characteristicIndex + ' uuid: ' + characteristic.uuid); | |
if ( characteristic.uuid === serialPortCharacteristicUUID ) { | |
serialPortCharacteristic = characteristic; | |
} | |
} | |
if ( !found && serialPortCharacteristic ) { | |
found = true; | |
var buf = new Buffer(10); | |
for (var i = 0; i < 10; i++) { | |
buf[i] = i + 1; | |
} | |
subscribe(); | |
setInterval(() => { send(buf); }, 1000); | |
} | |
}); | |
} | |
}); | |
}); | |
}); | |
function subscribe() { | |
console.log('--- SUBSCRIBE ---') | |
noble.stopScanning(); | |
serialPortCharacteristic.on('data', function(data, isNotification) { | |
console.log('--- read', isNotification, data.length, data); | |
}); | |
// No need to subscribe on ubuntu 16.04 LTS | |
serialPortCharacteristic.subscribe(function(err) { | |
console.log('--- subscribe'); | |
}); | |
} | |
function send(writeBuf) { | |
serialPortCharacteristic.write(writeBuf, false, function(err) { | |
if (err) console.log(err); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment