index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. let noble = require('noble');
  2. const ACCEL_OFF = Buffer.from([0x00]);
  3. const ACCEL_ON = Buffer.from([0x01]);
  4. // MAGIC CONSTANTS FOLLOW
  5. // these might be different for other devices, I wouldn't know
  6. const IDENTIFIER = 'CHSLEEV_00';
  7. const DEVICE_INFO_UUID = '180a';
  8. const ACCEL_UUID = 'ffa0';
  9. const TARE = 41690;
  10. const RATIO = 14;
  11. // MAGIC CONSTANTS END
  12. noble.on('stateChange', function(state) {
  13. if(state === 'poweredOn') {
  14. noble.startScanning();
  15. }
  16. else {
  17. noble.stopScanning();
  18. }
  19. });
  20. noble.on('discover', function(peripheral) {
  21. if(peripheral.advertisement.localName === 'CHSLEEV_00') {
  22. noble.stopScanning();
  23. console.log('Prep Pad found with address '+peripheral.address);
  24. peripheral.on('disconnect', function() {
  25. console.log('Disconnecting from Prep Pad '+peripheral.address);
  26. process.exit(0);
  27. });
  28. peripheral.connect(function(error) {
  29. console.log('Connected to Prep Pad');
  30. peripheral.discoverSomeServicesAndCharacteristics([DEVICE_INFO_UUID, ACCEL_UUID], [], function(error, services) {
  31. if(services.length != 2) {
  32. console.log('Could not find the relevant services. This might not actually be a Prep Pad');
  33. peripheral.disconnect();
  34. }
  35. else {
  36. let information = services[0];
  37. let accelerometer = services[1];
  38. information.characteristics[2].read(function(error, data) {
  39. console.log('Serial Number: '+data);
  40. });
  41. accelerometer.characteristics[0].write(ACCEL_ON);
  42. accelerometer.characteristics[2].subscribe();
  43. accelerometer.characteristics[2].on('data', function(data, isNotification) {
  44. let value = data[1] * 256 + data[0];
  45. let grams = Math.floor((TARE - value) / RATIO);
  46. console.log(grams+'g');
  47. });
  48. }
  49. });
  50. });
  51. }
  52. });