noble.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. var noble = require('noble');
  2. const ECHO_SERVICE_UUID = 'ec00';
  3. const ECHO_CHARACTERISTIC_UUID = 'ec0e';
  4. noble.on('stateChange', state => {
  5. if (state === 'poweredOn') {
  6. console.log('Scanning');
  7. noble.startScanning([ECHO_SERVICE_UUID]);
  8. } else {
  9. noble.stopScanning();
  10. }
  11. });
  12. noble.on('discover', peripheral => {
  13. // connect to the first peripheral that is scanned
  14. noble.stopScanning();
  15. const name = peripheral.advertisement.localName;
  16. console.log(`Connecting to '${name}' ${peripheral.id}`);
  17. connectAndSetUp(peripheral);
  18. });
  19. function connectAndSetUp(peripheral) {
  20. peripheral.connect(error => {
  21. // specify the services and characteristics to discover
  22. const serviceUUIDs = [ECHO_SERVICE_UUID];
  23. const characteristicUUIDs = [ECHO_CHARACTERISTIC_UUID];
  24. peripheral.discoverSomeServicesAndCharacteristics(
  25. serviceUUIDs,
  26. characteristicUUIDs,
  27. onServicesAndCharacteristicsDiscovered
  28. );
  29. });
  30. peripheral.on('disconnect', () => console.log('disconnected'));
  31. }
  32. function onServicesAndCharacteristicsDiscovered(error, services, characteristics) {
  33. console.log(123123123123123)
  34. console.log('Discovered services and characteristics');
  35. const echoCharacteristic = characteristics[0];
  36. // data callback receives notifications
  37. echoCharacteristic.on('data', (data, isNotification) => {
  38. console.log('Received: "' + data + '"');
  39. });
  40. // subscribe to be notified whenever the peripheral update the characteristic
  41. echoCharacteristic.subscribe(error => {
  42. if (error) {
  43. console.error('Error subscribing to echoCharacteristic');
  44. } else {
  45. console.log('Subscribed for echoCharacteristic notifications');
  46. }
  47. });
  48. // create an interval to send data to the service
  49. let count = 0;
  50. setInterval(() => {
  51. count++;
  52. const message = new Buffer('hello, ble ' + count, 'utf-8');
  53. console.log("Sending: '" + message + "'");
  54. echoCharacteristic.write(message);
  55. }, 2500);
  56. }