This repository has been archived by the owner on May 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
bluetooth.js
75 lines (64 loc) · 2.63 KB
/
bluetooth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var Event = require('cordova-plugin-chrome-apps-common.events');
var platform = cordova.require('cordova/platform');
var base64 = require('cordova/base64');
var exec = require('cordova/exec');
var callbackWithError = require('cordova-plugin-chrome-apps-common.errors').callbackWithError;
var fail = function(callback) {
return callback && function(msg) {
callbackWithError(msg, callback);
};
};
var convertServiceDataToArrayBuffer = function(deviceInfo) {
if (deviceInfo.serviceData) {
deviceInfo.serviceData = base64.toArrayBuffer(deviceInfo.serviceData);
}
return deviceInfo;
};
exports.getAdapterState = function(callback) {
exec(callback, fail(callback), 'ChromeBluetooth', 'getAdapterState', []);
};
exports.getDevice = function(deviceAddress, callback) {
var win = callback && function(device) {
callback(convertServiceDataToArrayBuffer(device));
};
exec(win, fail(callback), 'ChromeBluetooth', 'getDevice', [deviceAddress]);
};
exports.getDevices = function(callback) {
var win = callback && function(devices) {
callback(devices.map(convertServiceDataToArrayBuffer));
};
exec(win, fail(callback), 'ChromeBluetooth', 'getDevices', []);
};
exports.startDiscovery = function(callback) {
exec(callback, fail(callback), 'ChromeBluetooth', 'startDiscovery', []);
};
exports.stopDiscovery = function(callback) {
exec(callback, fail(callback), 'ChromeBluetooth', 'stopDiscovery', []);
};
exports.onAdapterStateChanged = new Event('onAdapterStateChanged');
exports.onDeviceAdded = new Event('onDeviceAdded');
exports.onDeviceChanged = new Event('onDeviceChanged');
exports.onDeviceRemoved = new Event('onDeviceRemoved');
function registerEvents() {
var onEventsCallback = function(eventType, info) {
switch (eventType) {
case 'onAdapterStateChanged':
exports.onAdapterStateChanged.fire(info);
break;
case 'onDeviceAdded':
exports.onDeviceAdded.fire(convertServiceDataToArrayBuffer(info));
break;
case 'onDeviceChanged':
exports.onDeviceChanged.fire(convertServiceDataToArrayBuffer(info));
break;
case 'onDeviceRemoved':
exports.onDeviceRemoved.fire(convertServiceDataToArrayBuffer(info));
break;
}
};
exec(onEventsCallback, null, 'ChromeBluetooth', 'registerBluetoothEvents', []);
}
require('cordova-plugin-chrome-apps-common.helpers').runAtStartUp(registerEvents);