@makefully/engagefully 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,440 @@
1
+ /* global console, navigator */
2
+ import BLECharacteristics from './specs/ble-characteristics.json';
3
+ import BLEDescriptors from './specs/ble-descriptors';
4
+ import BLEFormats from './specs/ble-formats';
5
+ import EventEmitter from 'events';
6
+
7
+ const
8
+ getDescriptorValue = (uuid, characteristic) => {
9
+ const
10
+ descriptors = characteristic?.descriptors;
11
+
12
+ if (descriptors) {
13
+ const
14
+ descriptor = descriptors.find((value) => value.uuid === uuid);
15
+
16
+ if (descriptor) {
17
+ return descriptor.value;
18
+ }
19
+ }
20
+
21
+ return null;
22
+ },
23
+ getCharacteristicUserDescription = (characteristic) => {
24
+ if (typeof characteristic === 'string') {
25
+ return characteristic;
26
+ } else {
27
+ return getDescriptorValue('2901', characteristic) || getDescriptorValue('00002904-0000-1000-8000-00805f9b34fb', characteristic);
28
+ }
29
+ },
30
+ getCharacteristicPresentationFormat = getDescriptorValue.bind(null, "2904"),
31
+ getControllerType = ({description}, customType = 'CustomType') => {
32
+ switch (description) {
33
+ case 'Reserved For Future Use':
34
+ return customType;
35
+ case 'Boolean':
36
+ return 'Button';
37
+ case 'UTF-8 string':
38
+ case 'UTF-16 string':
39
+ return 'Text';
40
+ case 'Opaque Structure':
41
+ return customType;
42
+ default:
43
+ return 'Amount'
44
+ }
45
+ };
46
+
47
+ let ble = null,
48
+ cordova = null;
49
+
50
+ try { // Put these in a try-catch so if we're in a cross-domain iframe, nothing breaks.
51
+ ble = window.ble || window.top.ble
52
+ cordova = window.cordova || window.top.cordova;
53
+ } catch (e) {}
54
+
55
+ class CordovaBLEDevice extends EventEmitter {
56
+ constructor (bluetoothDeviceOrOptions = {acceptAllDevices: true}, deviceName = 'BLEDevice', uuidMap = {}) {
57
+ super();
58
+
59
+ this.deviceName = deviceName;
60
+ this.uuidMap = {
61
+ ...BLECharacteristics,
62
+ ...uuidMap
63
+ };
64
+ this.ble = window.ble ?? window.top.ble;
65
+
66
+ this.writes = {};
67
+
68
+ if (bluetoothDeviceOrOptions?.id) { // It's a Bluetooth device
69
+ this.device = bluetoothDeviceOrOptions;
70
+ this.options = null;
71
+ } else {
72
+ this.device = null;
73
+ this.options = bluetoothDeviceOrOptions;
74
+ }
75
+ }
76
+
77
+ async initialize (options) {
78
+ if (!this.device) {
79
+ this.device = await this.requestDevice(options || this.options);
80
+ if (!this.device) {
81
+ throw "No device selected.";
82
+ }
83
+ }
84
+
85
+ const device = await this.connect();
86
+
87
+ if (device) {
88
+ const
89
+ characteristics = device.characteristics;
90
+
91
+ this.device = device;
92
+
93
+ characteristics.forEach(async (characteristic) => {
94
+ const
95
+ properties = characteristic.properties,
96
+ characteristicUUID = characteristic.characteristic.toLowerCase(), // iOS uses uppercase UUID's
97
+ characteristicDescription = this.uuidMap[characteristicUUID],
98
+ friendlyName = getCharacteristicUserDescription(characteristicDescription) || characteristicUUID,
99
+ descriptors = characteristic.descriptors || [],
100
+ format = BLEFormats[getCharacteristicPresentationFormat(characteristicDescription) || 0x1B]; // Assume "Opaque Structure" unless otherwise specified.
101
+
102
+ console.log(friendlyName, characteristic);
103
+
104
+ descriptors.forEach((descriptor) => {
105
+ console.log(`${descriptor.uuid} | ${friendlyName}`, descriptor);
106
+ });
107
+
108
+ if (properties.indexOf('Read') >= 0) {
109
+
110
+ }
111
+
112
+ if (properties.indexOf('Write') >= 0) {
113
+ if (this.writes[friendlyName]) {
114
+ throw new Error(`There is already a writable characteristic named "${friendlyName}".`)
115
+ }
116
+
117
+ this.writes[friendlyName] = (data) => {
118
+ return this.ble.withPromises.write(device.id, characteristic.service, characteristic.characteristic, data.buffer ?? data);
119
+ };
120
+ }
121
+
122
+ if (properties.indexOf('Notify') >= 0) {
123
+ const
124
+ type = getControllerType(format, friendlyName);
125
+ let lastValue = null;
126
+
127
+ this.ble.startNotification(device.id, characteristic.service, characteristic.characteristic, (buffer, index) => {
128
+ const
129
+ newValue = format.convert(new DataView(buffer));
130
+
131
+ if (lastValue !== newValue) {
132
+ lastValue = newValue;
133
+ this.emit('updated', {
134
+ control: friendlyName,
135
+ device: this.deviceName,
136
+ type,
137
+ value: newValue
138
+ });
139
+ }
140
+ }, (err) => {
141
+ throw err;
142
+ });
143
+ }
144
+ });
145
+ }
146
+ }
147
+
148
+ requestDevice (options) {
149
+ console.log('Requesting Device...');
150
+ return new Promise((resolve, reject) => {
151
+ console.log('Starting Scan... ');
152
+ if (cordova.platformId !== 'ios') {
153
+ this.ble.isLocationEnabled(() => {
154
+ console.log('Location is enabled');
155
+ }, () => {
156
+ console.log('Location is disabled');
157
+ });
158
+ }
159
+ this.ble.startScan((cordova.platformId === 'ios') ? options?.optionalServices ?? [] : [], (device) => { // TODO: Make possible to select from list instead of grabbing first one.
160
+ const services = options?.optionalServices ?? [];
161
+ let foundMatch = null;
162
+
163
+ console.log('Found', device);
164
+
165
+ if (cordova.platformId === 'ios') {
166
+ foundMatch = device;
167
+ } else {
168
+ const
169
+ a = new Uint8Array(device.advertising),
170
+ str = Array.prototype.map.call(a, (x) => ('00' + x.toString(16)).slice(-2)).join('');
171
+
172
+ console.log(str.match(/[a-fA-F0-9]{4}/g).join('-'));
173
+
174
+ services.forEach((value) => {
175
+ const
176
+ id = value.replace(/\-/g, '');
177
+
178
+ if (str.match(/[a-fA-F0-9]{2}/g).reverse().join('').indexOf(id) >= 0) {
179
+ foundMatch = device;
180
+ console.log(`Found a match! ${value}`);
181
+ }
182
+ });
183
+ }
184
+
185
+ if (foundMatch) {
186
+ this.ble.stopScan();
187
+ resolve(foundMatch);
188
+ }
189
+ }, (err) => {
190
+ console.log('Error', err);
191
+ this.ble.stopScan();
192
+ reject(err);
193
+ });
194
+ });
195
+ }
196
+
197
+ connect () {
198
+ return new Promise((resolve, reject) => {
199
+ if (!this.device) {
200
+ reject();
201
+ throw 'No device selected.';
202
+ } else {
203
+ this.ble.connect(this.device.id, (device) => {
204
+ this.emit('updated', {
205
+ control: `${this.deviceName}Connection`,
206
+ device: this.deviceName,
207
+ target: device,
208
+ type: 'Button',
209
+ value: 1
210
+ });
211
+ resolve(device);
212
+ }, () => {
213
+ console.log(`${this.deviceName} disconnected.`);
214
+ this.emit('updated', {
215
+ control: `${this.deviceName}Connection`,
216
+ device: this.deviceName,
217
+ type: 'Button',
218
+ value: 0
219
+ });
220
+ this.writes = {};
221
+ });
222
+ }
223
+ });
224
+ }
225
+
226
+ disconnect () {
227
+ this.ble.isConnected(this.device.id, () => {
228
+ this.ble.disconnect(this.device.id);
229
+ }, () => {
230
+ throw 'Device not connected.';
231
+ });
232
+ }
233
+
234
+ write (characteristicId, data) {
235
+ if (!this.writes[characteristicId]) {
236
+ throw new Error(`No writable characteristic "${characteristicId}".`);
237
+ }
238
+
239
+ return this.writes[characteristicId](data);
240
+ }
241
+ }
242
+
243
+ class WebkitBLEDevice extends EventEmitter {
244
+ constructor (bluetoothDeviceOrOptions = {acceptAllDevices: true}, deviceName = 'BLEDevice', uuidMap = {}) {
245
+ super();
246
+
247
+ this.deviceName = deviceName;
248
+ this.uuidMap = {
249
+ ...BLECharacteristics,
250
+ ...uuidMap
251
+ };
252
+
253
+ this.writes = {};
254
+
255
+ if (bluetoothDeviceOrOptions?.gatt) { // It's a Bluetooth device
256
+ this.device = bluetoothDeviceOrOptions;
257
+ this.options = null;
258
+ } else {
259
+ this.device = null;
260
+ this.options = bluetoothDeviceOrOptions;
261
+ }
262
+ }
263
+
264
+ async initialize (options) {
265
+ const
266
+ deviceAlreadySelected = !!this.device;
267
+
268
+ if (!deviceAlreadySelected) {
269
+ if (!navigator.bluetooth) {
270
+ throw "This web browser does not support Bluetooth.";
271
+ }
272
+
273
+ this.device = await navigator.bluetooth.requestDevice(options || this.options);
274
+
275
+ if (!this.device) {
276
+ throw "No device selected.";
277
+ }
278
+ }
279
+
280
+ this.device.addEventListener('gattserverdisconnected', () => {
281
+ console.log(`${this.deviceName} disconnected.`);
282
+ this.emit('updated', {
283
+ control: `${this.deviceName}Connection`,
284
+ device: this.deviceName,
285
+ type: 'Button',
286
+ value: 0
287
+ });
288
+ this.writes = {};
289
+ });
290
+
291
+ try {
292
+ if (await this.connect()) {
293
+ const
294
+ gatt = this.device.gatt,
295
+ services = await gatt.getPrimaryServices(),
296
+ presentationFormat = '00002904-0000-1000-8000-00805f9b34fb';
297
+
298
+ services.forEach(async (service) => {
299
+ const
300
+ characteristics = await service.getCharacteristics();
301
+
302
+ characteristics.forEach(async (characteristic) => {
303
+ const
304
+ properties = characteristic.properties,
305
+ characteristicDescription = this.uuidMap[characteristic.uuid],
306
+ friendlyName = getCharacteristicUserDescription(characteristicDescription) || characteristic.uuid;
307
+ let format = BLEFormats[0x1B]; // Assume "Opaque Structure" unless otherwise specified.
308
+
309
+ console.log(friendlyName, characteristic);
310
+
311
+ try {
312
+ const
313
+ descriptors = await characteristic.getDescriptors();
314
+ let formatFound = false;
315
+
316
+ descriptors.forEach(async (descriptor) => {
317
+ try {
318
+ const
319
+ value = (BLEDescriptors[descriptor.uuid] ?? BLEDescriptors['default']).convert(await descriptor.readValue());
320
+
321
+ if (descriptor.uuid === presentationFormat) {
322
+ format = BLEFormats[value] || BLEFormats[0];
323
+ formatFound = true;
324
+ }
325
+
326
+ console.log(`${descriptor.uuid} | ${friendlyName}`, value);
327
+ } catch (e) {
328
+ console.warn(`Error converting data from descriptor "${descriptor.uuid}".`, e);
329
+ }
330
+ });
331
+
332
+ if (!formatFound) {
333
+ const
334
+ localDefinition = getCharacteristicPresentationFormat(characteristicDescription);
335
+
336
+ if (localDefinition) {
337
+ format = BLEFormats[localDefinition];
338
+ }
339
+ }
340
+ } catch (e) {
341
+ }
342
+
343
+ if (properties.read) {
344
+
345
+ }
346
+
347
+ if (properties.write) {
348
+ if (this.writes[friendlyName]) {
349
+ throw new Error(`There is already a writable characteristic named "${friendlyName}".`)
350
+ }
351
+
352
+ this.writes[friendlyName] = (data) => {
353
+ const
354
+ dv = (data instanceof DataView) ? data : new DataView(data.buffer ?? data);
355
+
356
+ return characteristic.writeValueWithResponse(dv);
357
+ };
358
+ }
359
+
360
+ if (properties.notify) {
361
+ const
362
+ listener = (event) => {
363
+ const
364
+ target = event.currentTarget,
365
+ newValue = format.convert(target.value);
366
+
367
+ if (lastValue !== newValue) {
368
+ lastValue = newValue;
369
+ this.emit('updated', {
370
+ control: friendlyName,
371
+ device: this.deviceName,
372
+ type,
373
+ value: newValue
374
+ });
375
+ }
376
+ },
377
+ type = getControllerType(format, friendlyName);
378
+ let lastValue = null;
379
+
380
+ await characteristic.startNotifications();
381
+ characteristic.addEventListener('characteristicvaluechanged', listener);
382
+ }
383
+ });
384
+ });
385
+ } else {
386
+ throw "Not able to connect to device.";
387
+ }
388
+ } catch (e) {
389
+ if (!deviceAlreadySelected) { // We'll try anew next time.
390
+ if (this.device?.gatt?.connected) {
391
+ this.device.gatt.disconnect();
392
+ }
393
+ this.device = null;
394
+ }
395
+ throw e;
396
+ }
397
+ }
398
+
399
+ async connect () {
400
+ if (!this.device) {
401
+ throw 'No device selected.';
402
+ } else {
403
+ const
404
+ gatt = this.device.gatt;
405
+
406
+ await gatt.connect();
407
+
408
+ if (gatt.connected) {
409
+ this.emit('updated', {
410
+ control: `${this.deviceName}Connection`,
411
+ device: this.deviceName,
412
+ target: this.device,
413
+ type: 'Button',
414
+ value: 1
415
+ });
416
+ return true;
417
+ } else {
418
+ return false;
419
+ }
420
+ }
421
+ }
422
+
423
+ disconnect () {
424
+ if (this.device?.gatt?.connected) {
425
+ return this.device.gatt.disconnect();
426
+ } else {
427
+ throw 'Device not connected.';
428
+ }
429
+ }
430
+
431
+ write (characteristicId, data) {
432
+ if (!this.writes[characteristicId]) {
433
+ throw new Error(`No writable characteristic "${characteristicId}".`);
434
+ }
435
+
436
+ return this.writes[characteristicId](data);
437
+ }
438
+ }
439
+
440
+ export default ble ? CordovaBLEDevice : WebkitBLEDevice;
@@ -0,0 +1,97 @@
1
+ import EventEmitter from 'events';
2
+
3
+ class FabricDevice extends EventEmitter {
4
+ constructor (target, device = 'FabricDevice') {
5
+ super();
6
+
7
+ this.pressed = 0;
8
+
9
+ // FabricPointer
10
+ target.on('mousedown', (event) => {
11
+ this.pressed = 1;
12
+ this.emit('updated', {
13
+ control: 'FabricPointer',
14
+ device,
15
+ event,
16
+ target,
17
+ type: 'Pointer',
18
+ value: this.pressed,
19
+ x: event.pointer.x,
20
+ y: event.pointer.y
21
+ });
22
+ });
23
+
24
+ target.on('mousemove', (event) => {
25
+ this.emit('updated', {
26
+ control: 'FabricPointer',
27
+ device,
28
+ event,
29
+ target,
30
+ type: 'Pointer',
31
+ value: this.pressed,
32
+ x: event.pointer.x,
33
+ y: event.pointer.y
34
+ });
35
+ });
36
+
37
+ target.on('mouseup', (event) => {
38
+ this.pressed = 0;
39
+ this.emit('updated', {
40
+ control: 'FabricPointer',
41
+ device,
42
+ event,
43
+ target,
44
+ type: 'Pointer',
45
+ value: this.pressed,
46
+ x: event.pointer.x,
47
+ y: event.pointer.y
48
+ });
49
+ });
50
+
51
+ // FabricDrop
52
+ target.on('dropped', (event) => {
53
+ this.emit('updated', {
54
+ control: 'FabricDrop',
55
+ device,
56
+ event,
57
+ target,
58
+ type: 'Drop',
59
+ value: event.dropZone ? event.dropZone.dropZone : '',
60
+ x: event.dropZone ? event.dropZoneX : event.x,
61
+ y: event.dropZone ? event.dropZoneY : event.y
62
+ });
63
+
64
+ event.stopPropagation();
65
+ });
66
+
67
+ // FabricDrag
68
+ target.on('dragover', (event) => {
69
+ this.emit('updated', {
70
+ control: 'FabricDrag',
71
+ device,
72
+ event,
73
+ target,
74
+ type: 'Drop',
75
+ value: event.dropZone ? event.dropZone.dropZone : '',
76
+ x: event.dropZone ? event.dropZoneX : event.x,
77
+ y: event.dropZone ? event.dropZoneY : event.y
78
+ });
79
+
80
+ event.stopPropagation();
81
+ });
82
+
83
+ // FabricDial
84
+ target.on('rotating', (event) => {
85
+ this.emit('updated', {
86
+ control: 'FabricDial',
87
+ device,
88
+ event,
89
+ target,
90
+ type: 'Dial',
91
+ value: target.angle / 360
92
+ });
93
+ });
94
+ }
95
+ }
96
+
97
+ export default FabricDevice;