index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // (c) 2015 Don Coleman
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /* global ble, statusDiv, beatsPerMinute */
  15. /* jshint browser: true , devel: true*/
  16. // See BLE heart rate service http://goo.gl/wKH3X7
  17. var heartRate = {
  18. service: '180d',
  19. measurement: '2a37'
  20. };
  21. var app = {
  22. initialize: function() {
  23. this.bindEvents();
  24. },
  25. bindEvents: function() {
  26. document.addEventListener('deviceready', this.onDeviceReady, false);
  27. },
  28. onDeviceReady: function() {
  29. app.scan();
  30. },
  31. scan: function() {
  32. app.status("Scanning for Heart Rate Monitor");
  33. var foundHeartRateMonitor = false;
  34. function onScan(peripheral) {
  35. // this is demo code, assume there is only one heart rate monitor
  36. console.log("Found " + JSON.stringify(peripheral));
  37. foundHeartRateMonitor = true;
  38. ble.connect(peripheral.id, app.onConnect, app.onDisconnect);
  39. }
  40. function scanFailure(reason) {
  41. alert("BLE Scan Failed");
  42. }
  43. ble.scan([heartRate.service], 5, onScan, scanFailure);
  44. setTimeout(function() {
  45. if (!foundHeartRateMonitor) {
  46. app.status("Did not find a heart rate monitor.");
  47. }
  48. }, 5000);
  49. },
  50. onConnect: function(peripheral) {
  51. app.status("Connected to " + peripheral.id);
  52. ble.startNotification(peripheral.id, heartRate.service, heartRate.measurement, app.onData, app.onError);
  53. },
  54. onDisconnect: function(reason) {
  55. alert("Disconnected " + reason);
  56. beatsPerMinute.innerHTML = "...";
  57. app.status("Disconnected");
  58. },
  59. onData: function(buffer) {
  60. // assuming heart rate measurement is Uint8 format, real code should check the flags
  61. // See the characteristic specs http://goo.gl/N7S5ZS
  62. var data = new Uint8Array(buffer);
  63. beatsPerMinute.innerHTML = data[1];
  64. },
  65. onError: function(reason) {
  66. alert("There was an error " + reason);
  67. },
  68. status: function(message) {
  69. console.log(message);
  70. statusDiv.innerHTML = message;
  71. }
  72. };
  73. app.initialize();