-
Notifications
You must be signed in to change notification settings - Fork 1
/
webbluetooth.js
728 lines (668 loc) · 20.7 KB
/
webbluetooth.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
'use strict';
/**
* Bluetooth handling module, including main state machine loop.
* This module interacts with browser for bluetooth comunications and pairing, and with SenecaMSC object.
*/
const log = require('loglevel');
const utils = require('./utils');
var simulation = false;
var logging = false;
/*
* Bluetooth constants
*/
const BlueToothOWON = {
ServiceUuid: '0000fff0-0000-1000-8000-00805f9b34fb', // bluetooth service for Owon B41T+
NotificationsUuid: '0000fff4-0000-1000-8000-00805f9b34fb',
};
/*
* Internal state machine descriptions
*/
const State = {
NOT_CONNECTED: 'Not connected',
CONNECTING: 'Bluetooth device pairing...',
DEVICE_PAIRED: 'Device paired',
SUBSCRIBING: 'Bluetooth interfaces connecting...',
IDLE: 'Idle',
BUSY: 'Busy',
ERROR: 'Error',
STOPPING: 'Closing BT interfaces...',
STOPPED: 'Stopped',
METER_INIT: 'Meter connected',
METER_INITIALIZING: 'Reading meter state...'
};
class APIState {
constructor() {
this.state = State.NOT_CONNECTED;
this.prev_state = State.NOT_CONNECTED;
this.state_cpt = 0;
this.started = false; // State machine status
this.stopRequest = false; // To request disconnect
// last notification
this.response = null;
this.responseTimeStamp = new Date();
this.parsedResponse = null;
this.formattedResponse = '';
// bluetooth properties
this.charRead = null;
this.btService = null;
this.btDevice = null;
// general statistics for debugging
this.stats = {
"requests": 0,
"responses": 0,
"modbus_errors": 0,
"GATT disconnects": 0,
"exceptions": 0,
"subcribes": 0,
"commands": 0,
"responseTime": 0.0,
"lastResponseTime": 0.0,
"last_connect": new Date(2020, 1, 1).toISOString()
};
this.options = {
"forceDeviceSelection": true
}
}
}
let btState = new APIState();
/**
* Main loop of the meter handler.
* */
async function stateMachine() {
var nextAction;
var DELAY_MS = (simulation ? 20 : 450); // Update the status every X ms.
var TIMEOUT_MS = (simulation ? 1000 : 30000); // Give up some operations after X ms.
btState.started = true;
log.debug("Current state:" + btState.state);
// Consecutive state counted. Can be used to timeout.
if (btState.state == btState.prev_state) {
btState.state_cpt++;
} else {
btState.state_cpt = 0;
}
// Stop request from API
if (btState.stopRequest) {
btState.state = State.STOPPING;
}
log.debug("\State:" + btState.state);
switch (btState.state) {
case State.NOT_CONNECTED: // initial state on Start()
if (simulation) {
nextAction = fakePairDevice;
} else {
nextAction = btPairDevice;
}
break;
case State.CONNECTING: // waiting for connection to complete
nextAction = undefined;
break;
case State.DEVICE_PAIRED: // connection complete, acquire meter state
if (simulation) {
nextAction = fakeSubscribe;
} else {
nextAction = btSubscribe;
}
break;
case State.SUBSCRIBING: // waiting for Bluetooth interfaces
nextAction = undefined;
if (btState.state_cpt > (TIMEOUT_MS / DELAY_MS)) {
// Timeout, try to resubscribe
log.warn("Timeout in SUBSCRIBING");
btState.state = State.DEVICE_PAIRED;
btState.state_cpt = 0;
}
break;
case State.METER_INIT: // ready to communicate, acquire meter status
nextAction = meterInit;
break;
case State.METER_INITIALIZING: // reading the meter status
if (btState.state_cpt > (TIMEOUT_MS / DELAY_MS)) {
log.warn("Timeout in METER_INITIALIZING");
// Timeout, try to resubscribe
if (simulation) {
nextAction = fakeSubscribe;
} else {
nextAction = btSubscribe;
}
btState.state_cpt = 0;
}
nextAction = undefined;
break;
case State.IDLE: // ready to process commands from API
if (btState.command != null)
nextAction = processCommand;
else {
nextAction = refresh;
}
break;
case State.ERROR: // anytime an error happens
nextAction = disconnect;
break;
case State.BUSY: // while a command in going on
if (btState.state_cpt > (TIMEOUT_MS / DELAY_MS)) {
log.warn("Timeout in BUSY");
// Timeout, try to resubscribe
if (simulation) {
nextAction = fakeSubscribe;
} else {
nextAction = btSubscribe;
}
btState.state_cpt = 0;
}
nextAction = undefined;
break;
case State.STOPPING:
nextAction = disconnect;
break;
case State.STOPPED: // after a disconnector or Stop() request, stops the state machine.
nextAction = undefined;
break;
default:
break;
}
btState.prev_state = btState.state;
if (nextAction != undefined) {
log.debug("\tExecuting:" + nextAction.name);
try {
await nextAction();
}
catch (e) {
log.error("Exception in state machine", e);
}
}
if (btState.state != State.STOPPED) {
utils.sleep(DELAY_MS).then(() => stateMachine()); // Recheck status in DELAY_MS ms
}
else {
log.debug("\tTerminating State machine");
btState.started = false;
}
}
/**
* Called from state machine to execute a single command from btState.command property
* */
async function processCommand() {
try {
command.error = false;
command.pending = false;
btState.command = null;
btState.state = State.IDLE;
log.debug("\t\tCompleted command executed");
}
catch (err) {
log.error("** error while executing command: " + err);
btState.state = State.METER_INIT;
btState.stats["exceptions"]++;
if (err instanceof modbus.ModbusError)
btState.stats["modbus_errors"]++;
return;
}
}
/**
* Acquire the current mode and serial number of the device.
* */
async function meterInit() {
btState.state = State.IDLE;
}
/*
* Close the bluetooth interface (unpair)
* */
async function disconnect() {
btState.command = null;
try {
if (btState.btDevice != null) {
if (btState.btDevice?.gatt?.connected) {
log.warn("* Calling disconnect on btdevice");
// Avoid the event firing which may lead to auto-reconnect
btState.btDevice.removeEventListener('gattserverdisconnected', onDisconnected);
btState.btDevice.gatt.disconnect();
}
}
btState.btService = null;
}
catch { }
btState.state = State.STOPPED;
}
/**
* Event called by browser BT api when the device disconnect
* */
async function onDisconnected() {
log.warn("* GATT Server disconnected event, will try to reconnect *");
btState.btService = null;
btState.stats["GATT disconnects"]++;
btState.state = State.DEVICE_PAIRED; // Try to auto-reconnect the interfaces without pairing
}
/**
* Joins the arguments into a single buffer
* @returns {Buffer} concatenated buffer
*/
function arrayBufferConcat() {
var length = 0;
var buffer = null;
for (var i in arguments) {
buffer = arguments[i];
length += buffer.byteLength;
}
var joined = new Uint8Array(length);
var offset = 0;
for (i in arguments) {
buffer = arguments[i];
joined.set(new Uint8Array(buffer), offset);
offset += buffer.byteLength;
}
return joined.buffer;
}
var lastTimeStamp = 0;
/**
* Event called by bluetooth characteristics when receiving data
* @param {any} event
*/
function handleNotifications(event) {
var delay = 0;
let value = event.target.value;
if (value != null) {
log.debug('<< ' + utils.buf2hex(value.buffer));
if (btState.response != null) {
btState.response = arrayBufferConcat(btState.response, value.buffer);
} else {
btState.response = value.buffer.slice();
}
// Keep the event original timestamp !!
btState.responseTimeStamp = new Date(event.timeStamp);
if (lastTimeStamp > 0) {
delay = event.timeStamp - lastTimeStamp; // ms between notifications
} else {
delay = 0;
}
lastTimeStamp = event.timeStamp;
parseResponse(btState.response, btState.responseTimeStamp);
// Log the packets
if (logging) {
var packet = { 'notification': utils.buf2hex(btState.response), 'parsed': btState.parsedResponse };
var packets = window.localStorage.getItem("OwonBTTrace");
if (packets == null) {
packets = []; // initialize array
}
else {
packets = JSON.parse(packets); // Restore the json persisted object
}
packets.push(packet); // Add the new object
window.localStorage.setItem("OwonBTTrace", JSON.stringify(packets));
}
if (delay > 0) {
btState.stats["lastResponseTime"] = delay;
btState.stats["responseTime"] = (btState.stats["responseTime"] * (btState.stats["responses"]-1.0) + delay) / btState.stats["responses"];
}
btState.stats["responses"]++;
btState.response = null;
}
}
/* OWON */
const DCV = 0x0;
const ACV = 0x1;
const DCA = 0x2;
const ACA = 0x3;
const Ohm = 0x4;
const Cap = 0x5;
const Hz = 0x6;
const Duty = 0x7;
const TempC = 0x8;
const TempF = 0x9;
const Diode = 0xA;
const Continuity = 0xB;
const hFE = 0xC;
function formatParsedResponse(fun, measurement, scale, overload) {
var measure = "?";
var units = "";
switch (fun) {
case DCV:
measure = "Vdc=";
units = "V";
break;
case ACV:
measure = "Vac=";
units = "V";
break;
case DCA:
measure = "Idc=";
units = "A";
break;
case ACA:
units = "Iac=";
units = "A";
break;
case Ohm:
measure = "R=";
units = "Ohms";
break;
case Cap:
measure = "C=";
units = "F";
break;
case Hz:
measure = "Frequency=";
units = "Hz";
break;
case Duty:
measure = "Duty=";
units = "%";
break;
case TempC:
measure = "Temperature=";
units = "°C";
break;
case TempF:
measure = "Temperature=";
units = "F";
break;
case Diode:
measure = "Diode=";
units = "V";
break;
case Continuity:
measure = "Continuity=";
units = "Ohms";
break;
case hFE:
measure = "hFE=";
units = "";
break;
default:
measure = "?=";
units = "?";
break;
}
switch (scale) {
case 0:
scale = "";
break;
case 1:
scale = "n";
break;
case 2:
scale = "micro";
break;
case 3:
scale = "m";
break;
case 4:
scale = "";
break;
case 5:
scale = "kilo";
break;
case 6:
scale = "mega";
break;
}
if (overload) {
return measure + " **OVERLOAD** " + scale + units;
}
else {
return measure + measurement + " " + scale + units;
}
}
function parseResponse(buffer, timestamp) {
let value = new DataView(buffer);
var measurement = NaN;
// See README.md on https://github.com/DeanCording/owonb35
var func = (value.getUint16(0, true) >> 6) & 0x0f;
var decimal = value.getUint8(0) & 0x07;
var scale = (value.getUint8(0) >> 3) & 0x07;
var uint16val = value.getUint8(4) + 256 * value.getUint8(5);
if (uint16val < 0x7fff) {
measurement = uint16val / Math.pow(10.0, decimal);
} else {
measurement = -1.0 * (uint16val & 0x7fff) / Math.pow(10.0, decimal);
}
var overload = (decimal == 0x07);
var normalization = 1.0;
switch (scale) {
case 0:
normalization = 1.0;
break;
case 1:
normalization = 0.000000001;
break;
case 2:
normalization = 0.000001;
break;
case 3:
normalization = 0.001;
break;
case 4:
normalization = 1.0;
break;
case 5:
normalization = 1000.0;
break;
case 6:
normalization = 1000000.0;
break;
}
var functionDesc = '';
switch (func) {
case DCV:
functionDesc = "Voltage (DC) - V";
break;
case ACV:
functionDesc = "Voltage (AC) - V";
break;
case DCA:
functionDesc = "Current (DC) - A"
break;
case ACA:
functionDesc = "Current (AC) - A"
break;
case Ohm:
functionDesc = "Resistance - Ohms"
break;
case Cap:
functionDesc = "Capacitance - F"
break;
case Hz:
functionDesc = "Frequency - Hz"
break;
case Duty:
functionDesc = "Duty cycle - %"
break;
case TempC:
functionDesc = "Temperature - °C"
break;
case TempF:
functionDesc = "Temperature - °F";
break;
case Diode:
functionDesc = "Diode - V";
break;
case Continuity:
functionDesc = "Continuity - Ohms";
break;
case hFE:
functionDesc = "hFE";
break;
default:
functionDesc = "?";
break;
}
btState.parsedResponse = {
"Function": func,
"Function description": functionDesc,
"Measurement": measurement,
"Scale": scale,
"Overload": overload,
"Timestamp": timestamp,
"Value": measurement * normalization,
"DateTime": new Date(),
"Decimal": decimal
};
btState.formattedResponse = formatParsedResponse(func, measurement, scale, overload);
}
/**
* This function will succeed only if called as a consequence of a user-gesture
* E.g. button click. This is due to BlueTooth API security model.
* */
async function btPairDevice() {
btState.state = State.CONNECTING;
var forceSelection = true;
log.debug("btPairDevice(" + forceSelection + ")");
try {
if (typeof (navigator.bluetooth?.getAvailability) == 'function') {
const availability = await navigator.bluetooth.getAvailability();
if (!availability) {
log.error("Bluetooth not available in browser.");
throw new Error("Browser does not provide bluetooth");
}
}
var device = null;
// If not, request from user
if (device == null) {
device = await navigator.bluetooth
.requestDevice({
acceptAllDevices: true,
optionalServices: [BlueToothOWON.ServiceUuid]
});
}
btState.btDevice = device;
btState.state = State.DEVICE_PAIRED;
log.info("Bluetooth device " + device.name + " connected.");
await utils.sleep(500);
}
catch (err) {
log.warn("** error while connecting: " + err.message);
btState.btService = null;
if (btState.charRead != null) {
try {
btState.charRead.stopNotifications();
} catch (error) { }
}
btState.charRead = null;
btState.state = State.ERROR;
btState.stats["exceptions"]++;
}
}
async function fakePairDevice() {
btState.state = State.CONNECTING;
var forceSelection = true;
log.debug("fakePairDevice(" + forceSelection + ")");
try {
var device = { name: "FakeBTDevice", gatt: { connected: true } };
btState.btDevice = device;
btState.state = State.DEVICE_PAIRED;
log.info("Bluetooth device " + device.name + " connected.");
await utils.sleep(50);
}
catch (err) {
log.warn("** error while connecting: " + err.message);
btState.btService = null;
btState.charRead = null;
btState.state = State.ERROR;
btState.stats["exceptions"]++;
}
}
/**
* Once the device is available, initialize the service and the 2 characteristics needed.
* */
async function btSubscribe() {
try {
btState.state = State.SUBSCRIBING;
btState.stats["subcribes"]++;
let device = btState.btDevice;
let server = null;
if (!device?.gatt?.connected) {
log.debug(`Connecting to GATT Server on ${device.name}...`);
device.addEventListener('gattserverdisconnected', onDisconnected);
try {
if (btState.btService?.connected) {
btState.btService.disconnect();
btState.btService = null;
await utils.sleep(100);
}
} catch (err) { }
server = await device.gatt.connect();
log.debug('> Found GATT server');
}
else {
log.debug('GATT already connected');
server = device.gatt;
}
btState.btService = await server.getPrimaryService(BlueToothOWON.ServiceUuid);
if (btState.btService == null)
throw new Error("GATT Service request failed");
log.debug('> Found Owon service');
btState.charRead = await btState.btService.getCharacteristic(BlueToothOWON.NotificationsUuid);
log.debug('> Found notifications characteristic');
btState.response = null;
btState.charRead.addEventListener('characteristicvaluechanged', handleNotifications);
btState.charRead.startNotifications();
log.info('> Bluetooth interfaces ready.');
btState.stats["last_connect"] = new Date().toISOString();
await utils.sleep(50);
btState.state = State.METER_INIT;
}
catch (err) {
log.warn("** error while subscribing: " + err.message);
if (btState.charRead != null) {
try {
if (btState.btDevice?.gatt?.connected) {
btState.charRead.stopNotifications();
}
btState.btDevice?.gatt.disconnect();
} catch (error) { }
}
btState.charRead = null;
btState.state = State.DEVICE_PAIRED;
btState.stats["exceptions"]++;
}
}
async function fakeSubscribe() {
try {
btState.state = State.SUBSCRIBING;
btState.stats["subcribes"]++;
let device = btState.btDevice;
let server = null;
if (!device?.gatt?.connected) {
log.debug(`Connecting to GATT Server on ${device.name}...`);
device['gatt']['connected'] = true;
log.debug('> Found GATT server');
}
else {
log.debug('GATT already connected');
server = device.gatt;
}
btState.btService = {};
log.debug('> Found Serial service');
btState.charRead = {};
log.debug('> Found read characteristic');
btState.response = null;
log.info('> Bluetooth interfaces ready.');
btState.stats["last_connect"] = new Date().toISOString();
await utils.sleep(10);
btState.state = State.METER_INIT;
}
catch (err) {
log.warn("** error while subscribing: " + err.message);
btState.charRead = null;
btState.state = State.DEVICE_PAIRED;
btState.stats["exceptions"]++;
}
}
/**
* When idle, this function is called
* */
async function refresh() {
btState.state = State.BUSY;
// Do something
btState.state = State.IDLE;
}
function SetSimulation(value) {
simulation = value;
}
/**
* Enables or disable writing the notifications into a local storage file
* @param {boolean} value
*/
function SetPacketLog(value) {
logging = value;
}
module.exports = { stateMachine, SetSimulation, btState, State, SetPacketLog };