ITP | Week 3 | February 10, 2017
Don Coleman
try {
temperature = api.getTemperature();
console.log(temperature);
} catch(e) {
console.log("Error " + e);
}
synchronous API call
var success = function(temperature) {
console.log(temperature);
};
var failure = function(err) {
console.log("Error " + err);
};
api.getTemperature(success, failure);
Cordova APIs (usually) end with success and failure callbacks
Exercise 1
ble.scan(
[], // any services
5, // 5 seconds
onDiscoverDevice,
failure
);
var onDiscoverDevice = function(device) {
console.log(
device.name,
device.id,
device.rssi
);
}
Exercise 2
ble.connect(
device.id,
onConnection,
failure
);
var onConnection = function(peripheral) {
console.log(
JSON.stringify(peripheral)
);
}
Exercise 3
ble.scan(
[LED_SERVICE], // only led
5, // 5 seconds
onDiscoverDevice,
failure
);
setSwitchValue: function(value) {
var data = new Uint8Array(1);
data[0] = value;
// ...
},
Create typed array in setSwitchValue
ble.write(
app.peripheral.id,
LED_SERVICE,
SWITCH_CHARACTERISTIC,
data.buffer,
success,
app.onError
);
Write value to switch characteristic in setSwitchValue
var data = new Uint8Array(1);
data[0] = brightness.value;
ble.write(
app.peripheral.id,
LED_SERVICE,
BRIGHTNESS_CHARACTERISTIC,
data.buffer,
success,
app.onError
);
Write value to dimmer characteristic in setBrightness
Exercise 4
ble.startNotification(
device.id,
BUTTON_SERVICE,
STATUS_CHARACTERISTIC,
app.onNotification,
failure);
subscribe to be notified when the button state changes
onNotification: function(buffer) {
var data = new Uint8Array(buffer);
if (data[0] === 0) {
message = 'Button is released.';
} else {
message = 'Button is pressed.';
}
},
Exercise 5
ble.startNotification(
peripheral.id,
THERMOMETER_SERVICE,
TEMPERATURE_CHARACTERISTIC,
app.onTemperatureChange,
failure
);
subscribe to be notified when the temperature changes
ble.read(
peripheral.id,
THERMOMETER_SERVICE,
TEMPERATURE_CHARACTERISTIC,
app.onTemperatureChange,
failure
);
read the initial value
onTemperatureChange: function(buffer) {
var data = new Float32Array(buffer);
var celsius = data[0];
var fahrenheit = (celsius * 1.8 + 32.0);
var message = "Temperature is " +
fahrenheit + " °F";
statusDiv.innerHTML = message;
},
$ jshint www/js/index.js
www/js/index.js: line 26, col 33, Expected
an identifier and instead saw '5'.
1 error
window.onerror = function (e, fileName, lineNumber) {
console.log(fileName,
'Line:', lineNumber, '\n',
'Error:', e.message);
alert(fileName +
'Line:' + lineNumber, '\n',
'Error:' + e.message);
};
$ cd phonegap/led_v2
$ phonegap platform add ios
$ phonegap plugin add cordova-plugin-ble-central
$ phonegap plugin add cordova-plugin-dialogs
$ phonegap run ios --device
Don Coleman
dc159@nyu.edu
NYU ITP Bluetooth Spring 2017 Week 3 by Don Coleman is licensed under a Creative Commons Attribution 4.0 International License.