-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFlutterConnector.js
More file actions
925 lines (764 loc) · 28.7 KB
/
FlutterConnector.js
File metadata and controls
925 lines (764 loc) · 28.7 KB
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
import { logging } from "./Logging.js";
import { sleep, toBytes, detectTangleConnect, numberToBytes } from "./functions.js";
import { TimeTrack } from "./TimeTrack.js";
import { TnglReader } from "./TnglReader.js";
import { DEVICE_FLAGS, NETWORK_FLAGS, TangleInterface } from "./TangleInterface.js";
/////////////////////////////////////////////////////////////////////////////////////
var simulatedFails = false;
class FlutterConnection {
constructor() {
// @ts-ignore
if (window.flutterConnection) {
logging.debug("FlutterConnection already inited");
return;
}
logging.debug("Initing FlutterConnection");
// @ts-ignore
window.flutterConnection = {};
// @ts-ignore
window.flutterConnection.resolve = null;
// @ts-ignore
window.flutterConnection.reject = null;
// @ts-ignore
window.flutterConnection.emit = null;
// // target="_blank" global handler
// // @ts-ignore
// window.flutterConnection.hasOwnProperty("open") &&
// /** @type {HTMLBodyElement} */ (document.querySelector("body")).addEventListener("click", function (e) {
// e.preventDefault();
// // @ts-ignore
// for (let el of e.path) {
// if (el.tagName === "A" && el.getAttribute("target") === "_blank") {
// e.preventDefault();
// const url = el.getAttribute("href");
// // console.log(url);
// // @ts-ignore
// window.flutterConnection.open(url);
// break;
// }
// }
// });
if (this.available()) {
logging.debug("Flutter Connector available");
window.addEventListener("#resolve", e => {
// @ts-ignore
const value = e.detail.value;
logging.debug("Triggered #resolve:", typeof(value), value);
// @ts-ignore
window.flutterConnection.resolve(value);
});
window.addEventListener("#reject", e => {
// @ts-ignore
const value = e.detail.value;
logging.debug("Triggered #reject:", typeof(value), value);
// @ts-ignore
window.flutterConnection.reject(value);
});
window.addEventListener("#emit", e => {
// @ts-ignore
const event = e.detail.value;
logging.debug("Triggered #emit:", typeof(event), event);
// @ts-ignore
window.flutterConnection.emit(event);
});
window.addEventListener("#process", e => {
// @ts-ignore
const bytes = e.detail.value;
logging.debug("Triggered #process:", typeof(bytes), bytes);
// @ts-ignore
window.flutterConnection.process(bytes);
});
} else {
logging.debug("flutter_inappwebview in window NOT detected");
logging.info("Simulating Flutter Functions");
var _connected = false;
var _selected = false;
function _fail(failChance) {
if (simulatedFails) {
return Math.random() < failChance;
} else {
return false;
}
}
// @ts-ignore
window.flutter_inappwebview = {};
// @ts-ignore
window.flutter_inappwebview.callHandler = async function (handler, a, b, c, d) {
//
switch (handler) {
//
case "userSelect": // params: (criteria_json, timeout_number)
{
// disconnect if already connected
if (_connected) {
// @ts-ignore
await window.flutter_inappwebview.callHandler("disconnect");
}
await sleep(Math.random() * 5000); // do the userSelect task filtering devices by the criteria_json parameter
if (_fail(0.5)) {
// @ts-ignore
window.flutterConnection.reject("UserCanceledSelection"); // reject with "UserCanceledSelection" message if user cancels selection
return;
}
if (_fail(0.1)) {
// @ts-ignore
window.flutterConnection.reject("SelectionFailed");
return;
}
_selected = true;
// @ts-ignore
window.flutterConnection.resolve('{"connector":"tangleconnect"}');
}
break;
case "autoSelect": // params: (criteria_json, scan_period_number, timeout_number)
{
if (_connected) {
// @ts-ignore
await window.flutter_inappwebview.callHandler("disconnect"); // handle disconnection inside the flutter app
}
await sleep(Math.random() * 5000); // do the autoSelect task filtering devices by the criteria_json parameter and scanning minimum time scan_period_number, maximum timeout_number
if (_fail(0.1)) {
// @ts-ignore
window.flutterConnection.reject("SelectionFailed"); // if the selection fails, return "SelectionFailed"
return;
}
_selected = true;
// @ts-ignore
window.flutterConnection.resolve('{"connector":"tangleconnect"}'); // resolve with json containing the information about the connected device
}
break;
case "selected":
{
// params: ()
if (_selected) {
// @ts-ignore
window.flutterConnection.resolve('{"connector":"tangleconnect"}'); // if the device is selected, return json
} else {
// @ts-ignore
window.flutterConnection.resolve(); // if no device is selected resolve nothing
}
}
break;
case "unselect":
{
// params: ()
if (_connected) {
// @ts-ignore
await window.flutterConnection.disconnect();
}
await sleep(10); // unselect logic
_selected = false;
// @ts-ignore
window.flutterConnection.resolve();
}
break;
case "connect":
{
// params: (timeout_number)
if (!_selected) {
// @ts-ignore
window.flutterConnection.reject("DeviceNotSelected");
return;
}
await sleep(Math.random() * 5000); // connecting logic
if (_fail(0.1)) {
// @ts-ignore
window.flutterConnection.reject("ConnectionFailed");
return;
}
_connected = true;
// @ts-ignore
// @ts-ignore
window.flutterConnection.resolve('{"connector":"tangleconnect"}');
// after connection the TangleConnect can any time emit #disconnect event.
await sleep(1000); // unselect logic
// @ts-ignore
window.flutterConnection.emit("#connected");
setTimeout(() => {
// @ts-ignore
window.flutterConnection.emit("#disconnected");
//}, Math.random() * 60000);
_connected = false;
}, 60000);
}
break;
case "disconnect":
{
// params: ()
if (_connected) {
await sleep(100); // disconnecting logic
_connected = false;
// @ts-ignore
window.flutterConnection.emit("#disconnected");
}
// @ts-ignore
window.flutterConnection.resolve(); // always resolves even if there are internal errors
}
break;
case "connected":
{
// params: ()
if (_connected) {
// @ts-ignore
window.flutterConnection.resolve('{"connector":"tangleconnect"}');
} else {
// @ts-ignore
window.flutterConnection.resolve();
}
}
break;
case "deliver":
{
// params: (payload_bytes)
if (!_connected) {
// @ts-ignore
window.flutterConnection.reject("DeviceDisconnected");
return;
}
await sleep(25); // delivering logic
if (_fail(0.1)) {
// @ts-ignore
window.flutterConnection.reject("DeliverFailed");
return;
}
// @ts-ignore
window.flutterConnection.resolve();
}
break;
case "transmit":
{
// params: (payload_bytes)
if (!_connected) {
// @ts-ignore
window.flutterConnection.reject("DeviceDisconnected");
return;
}
await sleep(10); // transmiting logic
if (_fail(0.1)) {
// @ts-ignore
window.flutterConnection.reject("TransmitFailed");
return;
}
// @ts-ignore
window.flutterConnection.resolve();
}
break;
case "request":
{
// params: (payload_bytes, read_response)
if (!_connected) {
// @ts-ignore
window.flutterConnection.reject("DeviceDisconnected");
return;
}
await sleep(50); // requesting logic
if (_fail(0.1)) {
// @ts-ignore
window.flutterConnection.reject("RequestFailed");
return;
}
// @ts-ignore
window.flutterConnection.resolve([246, 1, 0, 0, 0, 188, 251, 18, 0, 212, 247, 18, 0, 0]); // returns data as an array of bytes: [0,255,123,89]
}
break;
case "writeClock":
{
// params: (clock_bytes)
if (!_connected) {
// @ts-ignore
window.flutterConnection.reject("DeviceDisconnected");
return;
}
await sleep(10); // writing clock logic.
if (_fail(0.1)) {
// @ts-ignore
window.flutterConnection.reject("ClockWriteFailed");
return;
}
// @ts-ignore
window.flutterConnection.resolve();
}
break;
case "readClock":
{
// params: ()
if (!_connected) {
// @ts-ignore
window.flutterConnection.reject("DeviceDisconnected");
return;
}
await sleep(50); // reading clock logic.
if (_fail(0.1)) {
// @ts-ignore
window.flutterConnection.reject("ClockReadFailed");
return;
}
// @ts-ignore
window.flutterConnection.resolve([0, 0, 0, 0]); // returns timestamp as an 32-bit signed number
}
break;
case "updateFW":
{
// params: (bytes)
if (!_connected) {
// @ts-ignore
window.flutterConnection.reject("DeviceDisconnected");
return;
}
// @ts-ignore
window.flutterConnection.emit("ota_status", "begin");
await sleep(10000); // preparing FW logic.
if (_fail(0.1)) {
// @ts-ignore
window.flutterConnection.emit("ota_status", "fail");
// @ts-ignore
window.flutterConnection.reject("UpdateFailed");
return;
}
for (let i = 1; i <= 100; i++) {
// @ts-ignore
window.flutterConnection.emit("ota_progress", i);
await sleep(25); // writing FW logic.
if (_fail(0.01)) {
// @ts-ignore
window.flutterConnection.emit("ota_status", "fail");
// @ts-ignore
window.flutterConnection.reject("UpdateFailed");
return;
}
}
await sleep(1000); // finishing FW logic.
if (_fail(0.1)) {
// @ts-ignore
window.flutterConnection.emit("ota_status", "fail");
// @ts-ignore
window.flutterConnection.reject("UpdateFailed");
return;
}
// @ts-ignore
window.flutterConnection.emit("ota_status", "success");
// @ts-ignore
window.flutterConnection.resolve();
}
break;
default:
logging.error("Unknown handler");
break;
}
};
}
}
available() {
return "flutter_inappwebview" in window;
}
}
// Connector connects the application with one Tangle Device, that is then in a
// position of a controller for other Tangle Devices
export class FlutterConnector extends FlutterConnection {
#interfaceReference;
#promise;
constructor(interfaceReference) {
super();
this.type = "tangleconnect";
this.#interfaceReference = interfaceReference;
this.#promise = null;
// @ts-ignore
window.flutterConnection.emit = event => {
this.#interfaceReference.emit(event, null);
};
// @ts-ignore
window.flutterConnection.process = bytes => {
this.#interfaceReference.process(new DataView(new Uint8Array(bytes).buffer));
};
}
#applyTimeout(promise, timeout, message) {
let id = setTimeout(() => {
// @ts-ignore
// window.alert(message, "Error: TC response timeouted");
// @ts-ignore
window.flutterConnection.reject("ResponseTimeout " + message);
}, timeout);
return promise.finally(() => {
clearTimeout(id);
});
}
async ping() {
console.time("ping_measure");
for (let i = 0; i < 1000; i++) {
this.#promise = new Promise((resolve, reject) => {
// @ts-ignore
window.flutterConnection.resolve = resolve;
// @ts-ignore
window.flutterConnection.reject = reject;
});
// logging.debug("ping")
// @ts-ignore
window.flutterConnection.ping();
await this.#promise;
// logging.debug("pong")
}
//
console.timeEnd("ping_measure");
return this.#applyTimeout(this.#promise, 10000, "ping");
}
/*
criteria: JSON pole objektu, kde plati: [{ tohle AND tamto AND toto } OR { tohle AND tamto }]
možnosti:
name: string
namePrefix: string
fwVersion: string
ownerSignature: string
productCode: number
adoptionFlag: bool
criteria example:
[
// all Devices that are named "NARA Aplha", are on 0.7.2 fw and are
// adopted by the owner with "baf2398ff5e6a7b8c9d097d54a9f865f" signature.
// Product code is 1 what means NARA Alpha
{
name:"NARA Alpha"
fwVersion:"0.7.2"
ownerSignature:"baf2398ff5e6a7b8c9d097d54a9f865f"
productCode:1
},
{
namePrefix:"NARA"
fwVersion:"!0.7.3"
productCode:2
adoptionFlag:true
}
]
*/
// choose one Tangle device (user chooses which device to connect to via a popup)
// if no criteria are set, then show all Tangle devices visible.
// first bonds the BLE device with the PC/Phone/Tablet if it is needed.
// Then selects the device
userSelect(criteria_object, timeout_number = 60000) {
const criteria_json = JSON.stringify(criteria_object);
logging.debug(`userSelect(criteria=${criteria_json}, timeout=${timeout_number})`);
this.#promise = new Promise((resolve, reject) => {
// @ts-ignore
window.flutterConnection.resolve = function (j) {
resolve(j ? JSON.parse(j) : null);
};
// @ts-ignore
window.flutterConnection.reject = reject;
});
// @ts-ignore
window.flutter_inappwebview.callHandler("userSelect", criteria_json, timeout_number);
return this.#applyTimeout(this.#promise, timeout_number * 2, "userSelect");
}
// takes the criteria, scans for scan_period and automatically selects the device,
// you can then connect to. This works only for BLE devices that are bond with the phone/PC/tablet
// the app is running on OR doesnt need to be bonded in a special way.
// if more devices are found matching the criteria, then the strongest signal wins
// if no device is found within the timeout period, then it returns an error
// if no criteria are provided, all Tangle enabled devices (with all different FWs and Owners and such)
// are eligible.
autoSelect(criteria_object, scan_period_number = 1000, timeout_number = 10000) {
// step 1. for the scan_period scan the surroundings for BLE devices.
// step 2. if some devices matching the criteria are found, then select the one with
// the greatest signal strength. If no device is found until the timeout,
// then return error
const criteria_json = JSON.stringify(criteria_object);
logging.debug(`autoSelect(criteria=${criteria_json}, scan_period=${scan_period_number}, timeout=${timeout_number})`);
this.#promise = new Promise((resolve, reject) => {
// @ts-ignore
window.flutterConnection.resolve = function (j) {
resolve(j ? JSON.parse(j) : null);
};
// @ts-ignore
window.flutterConnection.reject = reject;
});
// @ts-ignore
window.flutter_inappwebview.callHandler("autoSelect", criteria_json, scan_period_number, timeout_number);
return this.#applyTimeout(this.#promise, timeout_number * 2.0, "autoSelect");
}
selected() {
logging.debug(`selected()`);
this.#promise = new Promise((resolve, reject) => {
// @ts-ignore
window.flutterConnection.resolve = function (j) {
resolve(j ? JSON.parse(j) : null);
};
// @ts-ignore
window.flutterConnection.reject = reject;
});
// @ts-ignore
window.flutter_inappwebview.callHandler("selected");
return this.#applyTimeout(this.#promise, 1000);
}
unselect() {
logging.debug(`unselect()`);
this.#promise = new Promise((resolve, reject) => {
// @ts-ignore
window.flutterConnection.resolve = resolve;
// @ts-ignore
window.flutterConnection.reject = reject;
});
// @ts-ignore
window.flutter_inappwebview.callHandler("unselect");
return this.#applyTimeout(this.#promise, 1000, "unselect");
}
/*
timeout ms
*/
connect(timeout_number = 10000) {
logging.debug(`connect(timeout=${timeout_number})`);
if (timeout_number < 1000) {
logging.error("Invalid timeout. Must be more than 1000 ms.");
timeout_number = 1000;
}
this.#promise = new Promise((resolve, reject) => {
// @ts-ignore
window.flutterConnection.resolve = function (j) {
resolve(j ? JSON.parse(j) : null);
};
// @ts-ignore
window.flutterConnection.reject = reject;
});
// @ts-ignore
window.flutter_inappwebview.callHandler("connect", timeout_number);
return this.#applyTimeout(this.#promise, timeout_number < 5000 ? 10000 : timeout_number * 2, "connect").then(() => {
logging.debug("Sleeping for 200ms");
return sleep(200);
});
}
// disconnect Connector from the connected Tangle Device. But keep it selected
disconnect() {
logging.debug(`disconnect()`);
this.#promise = new Promise((resolve, reject) => {
// @ts-ignore
window.flutterConnection.resolve = resolve;
// @ts-ignore
window.flutterConnection.reject = reject;
});
// @ts-ignore
window.flutter_inappwebview.callHandler("disconnect");
return this.#applyTimeout(this.#promise, 10000, "disconnect");
}
connected() {
logging.debug(`connected()`);
this.#promise = new Promise((resolve, reject) => {
// @ts-ignore
window.flutterConnection.resolve = function (j) {
resolve(j ? JSON.parse(j) : null);
};
// @ts-ignore
window.flutterConnection.reject = reject;
});
// @ts-ignore
window.flutter_inappwebview.callHandler("connected");
return this.#applyTimeout(this.#promise, 1000, "connected");
}
// deliver handles the communication with the Tangle network in a way
// that the command is guaranteed to arrive
deliver(payload_bytes) {
logging.debug(`deliver(payload=[${payload_bytes}])`);
this.#promise = new Promise((resolve, reject) => {
// @ts-ignore
window.flutterConnection.resolve = resolve;
// @ts-ignore
window.flutterConnection.reject = reject;
});
// @ts-ignore
window.flutter_inappwebview.callHandler("deliver", payload_bytes);
return this.#applyTimeout(this.#promise, 10000, "deliver");
}
// transmit handles the communication with the Tangle network in a way
// that the command is NOT guaranteed to arrive
transmit(payload_bytes) {
logging.debug(`transmit(payload=[${payload_bytes}])`);
this.#promise = new Promise((resolve, reject) => {
// @ts-ignore
window.flutterConnection.resolve = resolve;
// @ts-ignore
window.flutterConnection.reject = reject;
});
// @ts-ignore
window.flutter_inappwebview.callHandler("transmit", payload_bytes);
return this.#applyTimeout(this.#promise, 10000, "transmit");
}
// request handles the requests on the Tangle network. The command request
// is guaranteed to get a response
request(payload_bytes, read_response = true) {
logging.debug(`request(payload=[${payload_bytes}], read_response=${read_response ? "true" : "false"})`);
this.#promise = new Promise((resolve, reject) => {
// @ts-ignore
window.flutterConnection.resolve = response => {
resolve(new DataView(new Uint8Array(response).buffer));
};
// @ts-ignore
window.flutterConnection.reject = reject;
});
// @ts-ignore
window.flutter_inappwebview.callHandler("request", payload_bytes, read_response);
return this.#applyTimeout(this.#promise, 10000, "request");
}
// synchronizes the device internal clock with the provided TimeTrack clock
// of the application as precisely as possible
setClock(clock) {
logging.debug("setClock()");
return new Promise(async (resolve, reject) => {
for (let index = 0; index < 3; index++) {
await sleep(1000);
try {
// tryes to ASAP write a timestamp to the clock characteristics.
// if the ASAP write fails, then try it once more
this.#promise = new Promise((resolve, reject) => {
// @ts-ignore
window.flutterConnection.resolve = resolve;
// @ts-ignore
window.flutterConnection.reject = reject;
});
const timestamp = clock.millis();
const clock_bytes = toBytes(timestamp, 4);
// @ts-ignore
window.flutter_inappwebview.callHandler("writeClock", clock_bytes);
await this.#applyTimeout(this.#promise, 5000, "writeClock");
logging.debug("Clock write success:", timestamp);
// @ts-ignore
resolve();
return;
} catch (e) {
logging.warn("Clock write failed: " + e);
}
}
reject("Clock write failed");
return;
});
}
// returns a TimeTrack clock object that is synchronized with the internal clock
// of the device as precisely as possible
getClock() {
logging.debug("getClock()");
return new Promise(async (resolve, reject) => {
for (let index = 0; index < 3; index++) {
try {
// tryes to ASAP read a timestamp from the clock characteristics.
// if the ASAP read fails, then try it once more
this.#promise = new Promise((resolve, reject) => {
// @ts-ignore
window.flutterConnection.resolve = resolve;
// @ts-ignore
window.flutterConnection.reject = reject;
});
// @ts-ignore
window.flutter_inappwebview.callHandler("readClock");
const bytes = await this.#applyTimeout(this.#promise, 5000, "readClock");
const reader = new TnglReader(new DataView(new Uint8Array(bytes).buffer));
const timestamp = reader.readInt32();
// const timestamp = await this.#promise;
logging.debug("Clock read success:", timestamp);
resolve(new TimeTrack(timestamp));
return;
} catch (e) {
logging.warn("Clock read failed:", e);
await sleep(1000);
}
}
reject("Clock read failed");
return;
});
}
// handles the firmware updating. Sends "ota" events
// to all handlers
// TODO - emit "ota_progress" events
updateFW(firmware_bytes) {
logging.debug(`updateFW(firmware_bytes.length=${firmware_bytes.length})`);
// this.#promise = new Promise((resolve, reject) => {
// // @ts-ignore
// window.flutterConnection.resolve = resolve;
// // @ts-ignore
// window.flutterConnection.reject = reject;
// });
// // @ts-ignore
// window.flutter_inappwebview.callHandler("updateFW", firmware_bytes);
// return this.#applyTimeout(this.#promise, 600000, "updateFW");
// logging.error("Device update is not yet implemented.");
// return Promise.reject("NotImplemented");
this.#interfaceReference.requestWakeLock();
return new Promise(async (resolve, reject) => {
const chunk_size = 3984; // must be modulo 16
// const chunk_size = 992; // must be modulo 16
let index_from = 0;
let index_to = chunk_size;
let written = 0;
logging.info("OTA UPDATE");
logging.verbose(firmware_bytes);
const start_timestamp = new Date().getTime();
await sleep(100);
try {
this.#interfaceReference.emit("ota_status", "begin");
{
//===========// RESET //===========//
logging.info("OTA RESET");
const device_bytes = [DEVICE_FLAGS.FLAG_OTA_RESET, 0x00, ...numberToBytes(0x00000000, 4)];
// const network_bytes = [NETWORK_FLAGS.FLAG_CONF_BYTES, ...numberToBytes(device_bytes.length, 4), ...device_bytes];
await this.request(device_bytes, false);
}
await sleep(100);
{
//===========// BEGIN //===========//
logging.info("OTA BEGIN");
const device_bytes = [DEVICE_FLAGS.FLAG_OTA_BEGIN, 0x00, ...numberToBytes(firmware_bytes.length, 4)];
// const network_bytes = [NETWORK_FLAGS.FLAG_CONF_BYTES, ...numberToBytes(device_bytes.length, 4), ...device_bytes];
await this.request(device_bytes, false);
}
await sleep(8000);
{
//===========// WRITE //===========//
logging.info("OTA WRITE");
while (written < firmware_bytes.length) {
if (index_to > firmware_bytes.length) {
index_to = firmware_bytes.length;
}
const device_bytes = [DEVICE_FLAGS.FLAG_OTA_WRITE, 0x00, ...numberToBytes(written, 4), ...firmware_bytes.slice(index_from, index_to)];
// const network_bytes = [NETWORK_FLAGS.FLAG_CONF_BYTES, ...numberToBytes(device_bytes.length, 4), ...device_bytes];
await this.request(device_bytes, false);
written += index_to - index_from;
const percentage = Math.floor((written * 10000) / firmware_bytes.length) / 100;
logging.debug(percentage + "%");
this.#interfaceReference.emit("ota_progress", percentage);
index_from += chunk_size;
index_to = index_from + chunk_size;
}
}
await sleep(100);
{
//===========// END //===========//
logging.info("OTA END");
const device_bytes = [DEVICE_FLAGS.FLAG_OTA_END, 0x00, ...numberToBytes(written, 4)];
// const network_bytes = [NETWORK_FLAGS.FLAG_CONF_BYTES, ...numberToBytes(device_bytes.length, 4), ...device_bytes];
await this.request(device_bytes, false);
}
await sleep(100);
logging.info("Rebooting device...");
const device_bytes = [DEVICE_FLAGS.FLAG_DEVICE_REBOOT_REQUEST];
// const network_bytes = [NETWORK_FLAGS.FLAG_CONF_BYTES, ...numberToBytes(device_bytes.length, 4), ...device_bytes];
await this.request(device_bytes, false);
logging.debug("Firmware written in " + (new Date().getTime() - start_timestamp) / 1000 + " seconds");
this.#interfaceReference.emit("ota_status", "success");
resolve(null);
} catch (e) {
this.#interfaceReference.emit("ota_status", "fail");
reject(e);
}
})
.then(() => {
return this.disconnect();
})
.finally(() => {
this.#interfaceReference.releaseWakeLock();
});
}
destroy() {
//this.#interfaceReference = null; // dont know if I need to destroy this reference.. But I guess I dont need to?
return this.disconnect()
.catch(() => {})
.then(() => {
return this.unselect();
})
.catch(() => {});
}
}