// (c) 2015 Don Coleman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* global ble, statusDiv, beatsPerMinute */ /* jshint browser: true , devel: true*/ // See BLE heart rate service http://goo.gl/wKH3X7 var heartRate = { service: "180d", measurement: "2a37" }; function stringToBytes(string) { var array = new Uint8Array(string.length); for (var i = 0, l = string.length; i < l; i++) { array[i] = string.charCodeAt(i); } return array.buffer; } var app = { initialize: function() { this.bindEvents(); }, bindEvents: function() { document.addEventListener("deviceready", this.onDeviceReady, false); }, onDeviceReady: function() { app.scan(); }, scan: function() { app.status("Scanning for Heart Rate Monitor"); var found = false; function onScan(device) { // this is demo code, assume there is only one heart rate monitor console.log("Found " + JSON.stringify(device)); found = true; if (device.name == "wifitest") { ble.connect(device.id, app.onConnect, app.onDisconnect); } } function scanFailure(reason) { alert("BLE Scan Failed"); } ble.scan([], 5, onScan, scanFailure); setTimeout(function() { if (!found) { app.status("Did not find a wifi config service."); } }, 5000); }, onConnect: function(peripheral) { app.status("Connected to " + peripheral.id); var data = stringToBytes("test"); ble.write( peripheral.id, "ffffffff-ffff-ffff-ffff-fffffffffff0", "ffffffff-ffff-ffff-ffff-fffffffffff1", data, function() { console.log("success"); }, function(error) { console.log(error); } ); }, onDisconnect: function(reason) { alert("Disconnected " + reason); beatsPerMinute.innerHTML = "..."; app.status("Disconnected"); }, onData: function(buffer) { // assuming heart rate measurement is Uint8 format, real code should check the flags // See the characteristic specs http://goo.gl/N7S5ZS var data = new Uint8Array(buffer); beatsPerMinute.innerHTML = data[1]; }, onError: function(reason) { alert("There was an error " + reason); }, status: function(message) { console.log(message); statusDiv.innerHTML = message; } }; app.initialize();