This repository was archived by the owner on Jul 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.js
More file actions
1553 lines (1292 loc) · 45.4 KB
/
code.js
File metadata and controls
1553 lines (1292 loc) · 45.4 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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2012 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview JavaScript for Blockly's Code demo.
* @author fraser@google.com (Neil Fraser)
*/
/// <reference path="lib/tangle-js/TangleWebBluetoothConnector.js" />
/// <reference path="blockly/blockly_compressed.js" />
/// <reference path="lib/tangle-js/TangleParser.js" />
/// <reference path="lib/tangle-js/TimeTrack.js" />
/// <reference path="lib/tangle-js/functions.js" />
"use strict";
if (!("TextDecoder" in window)) {
alert("Sorry, this browser does not support this app. TextDecoder isn't available.");
}
// if (!navigator.bluetooth) {
// alert("Oops, bluetooth doesn't work here.");
// }
// document.addEventListener("DOMContentLoaded", () => {
// // butConnect.addEventListener("click", clickConnect);
// // CODELAB: Add feature detection here.
// const notSupported = document.getElementById("notSupported");
// notSupported.classList.toggle("hidden", "serial" in navigator);
// });
/**
* Create a namespace for the application.
*/
var Code = {};
Code.revealConsole = function () {
enableDebugMode();
};
Code.hideConsole = function () {
deactivateDebugMode();
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Code.device = new TangleDevice("default", 0);
Code.device.setDebugLevel(5);
setTimeout(() => {
Code.device.setDebugLevel(5);
}, 1000);
const devices_textarea = document.querySelector("#devices_textarea");
Code.device.on("peer_connected", peer => {
console.log("Peer connected", peer);
var re = new RegExp(peer + "[✅❌]\\n", "gi");
if (devices_textarea.value.match(re)) {
devices_textarea.value = devices_textarea.value.replace(re, peer + "✅\n");
} else {
devices_textarea.value += peer + "✅\n";
}
});
Code.device.on("peer_disconnected", peer => {
console.log("Peer disconnected", peer);
var re = new RegExp(peer + "[✅❌]\\n", "gi");
if (devices_textarea.value.match(re)) {
devices_textarea.value = devices_textarea.value.replace(re, peer + "❌\n");
} else {
devices_textarea.value += peer + "❌\n";
}
});
Code.device.addEventListener("connected", event => {
console.log("Tangle Device connected");
Code.device.getConnectedPeersInfo().then(peers => {
devices_textarea.value = "";
for (let i = 0; i < peers.length; i++) {
devices_textarea.value += peers[i].mac + "✅\n";
}
});
const button = /** @type {HTMLButtonElement} */ (document.getElementById("connectBluetoothButton"));
const icon = /** @type {Element} */ (button.childNodes[1]);
icon.classList.remove("connect");
icon.classList.add("disconnect");
});
Code.device.addEventListener("disconnected", event => {
console.log("Tangle Device disconnected");
devices_textarea.value = "Devices disconnected";
const button = /** @type {HTMLButtonElement} */ (document.getElementById("connectBluetoothButton"));
const icon = /** @type {Element} */ (button.childNodes[1]);
icon.classList.remove("disconnect");
icon.classList.add("connect");
});
Code.device.addEventListener("version", ver => {
alert("Detected version: " + ver);
});
Code.device.addEventListener("ota_status", status => {
const container = document.getElementById("otaProgress");
const bar = document.getElementById("otaProgressBar");
const timeleft = document.getElementById("otaTimeLeft");
switch (status) {
case "begin":
container.style.display = "block";
bar.style.width = "0%";
bar.style.backgroundColor = "#008000";
timeleft.style.display = "block";
break;
case "success":
bar.style.width = "100%";
bar.style.backgroundColor = "#00a000";
alert("OTA update was successful");
break;
case "fail":
bar.style.backgroundColor = "#a00000";
alert("OTA update failed");
default:
break;
}
});
Code.device.addEventListener("ota_timeleft", timeleft => {
let min = Math.floor(timeleft / 60000);
timeleft %= 60000;
let sec = Math.floor(timeleft / 1000);
const pad = (number, size) => {
var s = String(number);
while (s.length < (size || 2)) {
s = "0" + s;
}
return s;
};
document.getElementById("otaTimeLeft").innerHTML = "Time left: " + min + ":" + pad(sec, 2);
});
Code.device.addEventListener("ota_progress", percentage => {
const bar = document.getElementById("otaProgressBar");
bar.style.width = percentage + "%";
});
function toggleUIConnected(connected) {
if (connected) {
//$("#connectSerialButton img").attr("class", "disconnect icon21");
document.getElementById("connectSerialButton").getElementsByTagName("img")[0].className = "disconnect icon21";
} else {
//$("#connectSerialButton img").attr("class", "connect icon21");
document.getElementById("connectSerialButton").getElementsByTagName("img")[0].className = "connect icon21";
}
}
function int32ToBytes(x) {
// we want to represent the input as a 4-bytes array
var byteArray = [0, 0, 0, 0];
for (var index = 0; index < byteArray.length; index++) {
var byte = x & 0xff;
byteArray[index] = byte;
x = (x - byte) / 256;
}
return byteArray;
}
function uint32ToBytes(x) {
return int32ToBytes(x);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Code.deviceManager = new TangleDeviceManager();
/**
* Lookup for names of supported languages. Keys should be in ISO 639 format.
*/
Code.LANGUAGE_NAME = {
ar: "العربية",
"be-tarask": "Taraškievica",
br: "Brezhoneg",
ca: "Català",
cs: "Česky",
da: "Dansk",
de: "Deutsch",
el: "Ελληνικά",
en: "English",
es: "Español",
et: "Eesti",
fa: "فارسی",
fr: "Français",
he: "עברית",
hrx: "Hunsrik",
hu: "Magyar",
ia: "Interlingua",
is: "Íslenska",
it: "Italiano",
ja: "日本語",
kab: "Kabyle",
ko: "한국어",
mk: "Македонски",
ms: "Bahasa Melayu",
nb: "Norsk Bokmål",
nl: "Nederlands, Vlaams",
oc: "Lenga d'òc",
pl: "Polski",
pms: "Piemontèis",
"pt-br": "Português Brasileiro",
ro: "Română",
ru: "Русский",
sc: "Sardu",
sk: "Slovenčina",
sr: "Српски",
sv: "Svenska",
ta: "தமிழ்",
th: "ภาษาไทย",
tlh: "tlhIngan Hol",
tr: "Türkçe",
uk: "Українська",
vi: "Tiếng Việt",
"zh-hans": "简体中文",
"zh-hant": "正體中文",
};
/**
* List of RTL languages.
*/
Code.LANGUAGE_RTL = ["ar", "fa", "he", "lki"];
/**
* Blockly's main workspace.
* @type {Blockly.WorkspaceSvg}
*/
Code.workspace = null;
Code.debug = {};
Code.debug.textarea = document.getElementById("content_debug");
Code.debug.setVisible = function (enable) {
if (enable) {
//console.log("enabling");
Code.debug.textarea.style.display = "block";
} else {
//console.log("disabling");
Code.debug.textarea.style.display = "none";
}
};
Code.device.on("receive", message => {
Code.debug.textarea.textContent += message.payload;
});
Code.device.on("event", event => {
console.log("Catched event:", event);
});
Code.rssi = {};
Code.device.on("rssi_data", event => {
Code.rssi[event.device_mac] = event.rssi;
// console.log(Code.rssi);
let array = [];
for (let key in Code.rssi) {
// console.log(key, Code.rssi[key]);
let item = {};
item.device_mac = key;
item.rssi = Code.rssi[key];
array.push(item);
}
console.log(array);
});
Code.control = {
div: /** @type {HTMLDivElement} */ (document.querySelector("#content_control")),
};
Code.control.setVisible = function (enable) {
if (enable) {
//console.log("enabling");
Code.control.div.style.display = "block";
} else {
//console.log("disabling");
Code.control.div.style.display = "none";
}
};
// Code.music = /** @type {HTMLAudioElement} */ (document.getElementById("timeline-old"));
// Code.metronome = new Audio();
// Code.device.timeline = new TimeTrack();
// Code.bank = 0;
// function sleep(ms) {
// return new Promise((resolve) => setTimeout(resolve, ms));
// }
// setInterval(async function () {
// Code.device.syncTimeline();
// }, 10000);
// Code.music.addEventListener("timeupdate", () => {
// Code.device.timeline.setMillis(Code.music.currentTime * 1000);
// Code.device.syncTimeline();
// });
// Code.music.addEventListener("play", () => {
// Code.device.timeline.unpause();
// Code.device.timeline.setMillis(Code.music.currentTime * 1000);
// // if (Code.metronome.src) {
// // Code.metronome.currentTime = Code.music.currentTime;
// // Code.metronome.play();
// // }
// Code.device.syncTimeline();
// });
// Code.music.addEventListener("pause", () => {
// Code.device.timeline.pause();
// Code.device.timeline.setMillis(Code.music.currentTime * 1000);
// // if (Code.metronome.src) {
// // Code.metronome.pause();
// // }
// Code.device.syncTimeline();
// });
Code.play = async function () {
console.log("Play");
Code.device.timeline.unpause();
// Code.device.timeline.setMillis(wavesurfer.getCurrentTime() * 1000);
wavesurfer.play();
// Code.device.syncTimeline();
};
Code.cycle = async function () {
console.log("Cycle");
wavesurfer.seekAndCenter(0);
Code.device.timeline.setMillis(0);
// Code.device.syncTimeline();
};
Code.pause = async function () {
console.log("Pause");
Code.device.timeline.pause();
// Code.device.timeline.setMillis(wavesurfer.getCurrentTime() * 1000);
wavesurfer.pause();
const dur = wavesurfer.getDuration();
const pos = dur ? wavesurfer.getCurrentTime() / wavesurfer.getDuration() : 0;
wavesurfer.seekAndCenter(pos);
// Code.device.syncTimeline();
};
Code.stop = async function () {
console.log("Stop");
Code.device.timeline.pause();
// Code.device.timeline.setMillis(0);
wavesurfer.pause();
wavesurfer.stop();
// Code.device.syncTimeline();
};
Code.upload = async function () {
console.log("Upload");
let xml_code = Blockly.Xml.domToPrettyText(Blockly.Xml.workspaceToDom(Code.workspace));
window.localStorage.setItem("blocks", xml_code);
var code = Blockly.Tngl.workspaceToCode(Code.workspace);
// console.log(tngl_bytes);
//prompt("Copy to clipboard: Ctrl+C, Enter", tngl_bytes);
Code.device.writeTngl(code).catch(e => console.error(e));
};
/**
* Extracts a parameter from the URL.
* If the parameter is absent default_value is returned.
* @param {string} name The name of the parameter.
* @param {string} defaultValue Value to return if parameter not found.
* @return {string} The parameter value or the default value if not found.
*/
Code.getStringParamFromUrl = function (name, defaultValue) {
var val = location.search.match(new RegExp("[?&]" + name + "=([^&]+)"));
return val ? decodeURIComponent(val[1].replace(/\+/g, "%20")) : defaultValue;
};
/**
* Get the language of this user from the URL.
* @return {string} User's language.
*/
Code.getLang = function () {
var lang = Code.getStringParamFromUrl("lang", "");
if (Code.LANGUAGE_NAME[lang] === undefined) {
// Default to Czech.
lang = "cs";
}
return lang;
};
/**
* Is the current language (Code.LANG) an RTL language?
* @return {boolean} True if RTL, false if LTR.
*/
Code.isRtl = function () {
return Code.LANGUAGE_RTL.indexOf(Code.LANG) != -1;
};
/**
* Load blocks saved on App Engine Storage or in session/local storage.
* @param {string} defaultXml Text representation of default blocks.
*/
Code.loadBlocks = function (defaultXml) {
try {
var loadOnce = window.sessionStorage.loadOnceBlocks;
} catch (e) {
// Firefox sometimes throws a SecurityError when accessing sessionStorage.
// Restarting Firefox fixes this, so it looks like a bug.
var loadOnce = null;
}
if ("BlocklyStorage" in window && window.location.hash.length > 1) {
// An href with #key trigers an AJAX call to retrieve saved blocks.
BlocklyStorage.retrieveXml(window.location.hash.substring(1));
} else if (loadOnce) {
// Language switching stores the blocks during the reload.
delete window.sessionStorage.loadOnceBlocks;
var xml = Blockly.Xml.textToDom(loadOnce);
Blockly.Xml.domToWorkspace(xml, Code.workspace);
} else if (defaultXml) {
// Load the editor with default starting blocks.
var xml = Blockly.Xml.textToDom(defaultXml);
Blockly.Xml.domToWorkspace(xml, Code.workspace);
} else if ("BlocklyStorage" in window) {
// Restore saved blocks in a separate thread so that subsequent
// initialization is not affected from a failed load.
window.setTimeout(BlocklyStorage.restoreBlocks, 0);
}
};
/**
* Changes the output language by clicking the tab matching
* the selected language in the codeMenu.
*/
Code.changeCodingLanguage = function () {
var codeMenu = document.getElementById("code_menu");
Code.tabClick(codeMenu.options[codeMenu.selectedIndex].value);
};
/**
* Bind a function to a button's click event.
* On touch enabled browsers, ontouchend is treated as equivalent to onclick.
* @param {!Element|string} el Button element or ID thereof.
* @param {!Function} func Event handler to bind.
*/
Code.bindClick = function (el, func) {
if (typeof el == "string") {
el = document.getElementById(el);
}
el.addEventListener("click", func, true);
//el.addEventListener('touchend', func, true);
};
// /**
// * Load the Prettify CSS and JavaScript.
// */
// Code.importPrettify = function () {
// var script = document.createElement("script");
// script.setAttribute("src", "https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js");
// document.head.appendChild(script);
// };
/**
* Compute the absolute coordinates and dimensions of an HTML element.
* @param {!Element} element Element to match.
* @return {!Object} Contains height, width, x, and y properties.
* @private
*/
Code.getBBox_ = function (element) {
var height = element.offsetHeight;
var width = element.offsetWidth;
var x = 0;
var y = 0;
do {
x += element.offsetLeft;
y += element.offsetTop;
element = element.offsetParent;
} while (element);
return {
height: height,
width: width,
x: x,
y: y,
};
};
/**
* User's language (e.g. "en").
* @type {string}
*/
Code.LANG = Code.getLang();
/**
* List of tab names.
* @private
*/
//Code.TABS_ = ['blocks', 'javascript', 'php', 'python', 'dart', 'lua', 'xml'];
Code.TABS_ = ["blocks", "tngl", "xml", "debug", "control"];
/**
* List of tab names with casing, for display in the UI.
* @private
*/
Code.TABS_DISPLAY_ = [
// 'Blocks', 'JavaScript', 'PHP', 'Python', 'Dart', 'Lua', 'XML',
"Blocks",
"Tngl",
"XML",
"Debug",
"Control",
];
Code.selected = "blocks";
/**
* Switch the visible pane when a tab is clicked.
* @param {string} clickedName Name of tab clicked.
*/
Code.tabClick = function (clickedName) {
// If the XML tab was open, save and render the content.
if (document.getElementById("tab_xml").classList.contains("tabon")) {
var xmlTextarea = document.getElementById("content_xml");
var xmlText = xmlTextarea.value;
var xmlDom = null;
try {
xmlDom = Blockly.Xml.textToDom(xmlText);
} catch (e) {
var q = window.confirm(MSG["badXml"].replace("%1", e));
if (!q) {
// Leave the user on the XML tab.
return;
}
}
if (xmlDom) {
Code.workspace.clear();
Blockly.Xml.domToWorkspace(xmlDom, Code.workspace);
}
}
if (document.getElementById("tab_blocks").classList.contains("tabon")) {
Code.workspace.setVisible(false);
}
if (document.getElementById("tab_debug").classList.contains("tabon")) {
Code.debug.setVisible(false);
}
// if (document.getElementById("tab_control").classList.contains("tabon")) {
// Code.control.setVisible(false);
// }
// Deselect all tabs and hide all panes.
for (var i = 0; i < Code.TABS_.length; i++) {
var name = Code.TABS_[i];
var tab = document.getElementById("tab_" + name);
tab.classList.add("taboff");
tab.classList.remove("tabon");
document.getElementById("content_" + name).style.visibility = "hidden";
}
// Select the active tab.
Code.selected = clickedName;
var selectedTab = document.getElementById("tab_" + clickedName);
selectedTab.classList.remove("taboff");
selectedTab.classList.add("tabon");
// Show the selected pane.
document.getElementById("content_" + clickedName).style.visibility = "visible";
Code.renderContent();
// The code menu tab is on if the blocks tab is off.
var codeMenuTab = document.getElementById("tab_code");
if (clickedName == "blocks") {
Code.workspace.setVisible(true);
codeMenuTab.className = "taboff";
} else {
codeMenuTab.className = "tabon";
}
// Sync the menu's value with the clicked tab value if needed.
var codeMenu = document.getElementById("code_menu");
for (var i = 0; i < codeMenu.options.length; i++) {
if (codeMenu.options[i].value == clickedName) {
codeMenu.selectedIndex = i;
break;
}
}
//Blockly.svgResize(Code.workspace);
};
/**
* Populate the currently selected pane with content generated from the blocks.
*/
Code.renderContent = function () {
var content = document.getElementById("content_" + Code.selected);
// Initialize the pane.
if (content.id == "content_xml") {
var xmlTextarea = document.getElementById("content_xml");
var xmlDom = Blockly.Xml.workspaceToDom(Code.workspace);
var xmlText = Blockly.Xml.domToPrettyText(xmlDom);
xmlTextarea.value = xmlText;
xmlTextarea.focus();
} else if (content.id == "content_tngl") {
var tnglTextarea = document.getElementById("content_tngl");
tnglTextarea.value = "";
if (Code.checkAllGeneratorFunctionsDefined(Blockly.Tngl)) {
tnglTextarea.value = Blockly.Tngl.workspaceToCode(Code.workspace);
// Remove the 'prettyprinted' class, so that Prettify will recalculate.
//content.className = content.className.replace("prettyprinted", "");
}
tnglTextarea.focus();
} else if (content.id == "content_debug") {
Code.debug.setVisible(true);
var debugTextarea = document.getElementById("content_debug");
// var xmlDom = Blockly.Xml.workspaceToDom(Code.workspace);
// var xmlText = Blockly.Xml.domToPrettyText(xmlDom);
debugTextarea.focus();
} else if (content.id == "content_control") {
Code.control.setVisible(true);
}
};
/**
* Check whether all blocks in use have generator functions.
* @param generator {!Blockly.Generator} The generator to use.
*/
Code.checkAllGeneratorFunctionsDefined = function (generator) {
var blocks = Code.workspace.getAllBlocks(false);
var missingBlockGenerators = [];
for (var i = 0; i < blocks.length; i++) {
var blockType = blocks[i].type;
if (!generator[blockType]) {
if (missingBlockGenerators.indexOf(blockType) == -1) {
missingBlockGenerators.push(blockType);
}
}
}
var valid = missingBlockGenerators.length == 0;
if (!valid) {
var msg = "The generator code for the following blocks not specified for " + generator.name_ + ":\n - " + missingBlockGenerators.join("\n - ");
Blockly.alert(msg); // Assuming synchronous. No callback.
}
return valid;
};
/**
* Initialize Blockly. Called on page load.
*/
Code.init = function () {
Code.initLanguage();
var rtl = Code.isRtl();
var container = document.getElementById("content_area");
var onresize = function (e) {
var bBox = Code.getBBox_(container);
for (var i = 0; i < Code.TABS_.length; i++) {
var el = document.getElementById("content_" + Code.TABS_[i]);
el.style.top = bBox.y + "px";
el.style.left = bBox.x + "px";
// Height and width need to be set, read back, then set again to
// compensate for scrollbars.
el.style.height = bBox.height + "px";
el.style.height = 2 * bBox.height - el.offsetHeight + "px";
el.style.width = bBox.width + "px";
el.style.width = 2 * bBox.width - el.offsetWidth + "px";
}
// Make the 'Blocks' tab line up with the toolbox.
if (Code.workspace && Code.workspace.getToolbox().width) {
document.getElementById("tab_blocks").style.minWidth = Code.workspace.getToolbox().width - 38 + "px";
// Account for the 19 pixel margin and on each side.
}
};
window.addEventListener("resize", onresize, false);
// The toolbox XML specifies each category name using Blockly's messaging
// format (eg. `<category name="%{BKY_CATLOGIC}">`).
// These message keys need to be defined in `Blockly.Msg` in order to
// be decoded by the library. Therefore, we'll use the `MSG` dictionary that's
// been defined for each language to import each category name message
// into `Blockly.Msg`.
// TODO: Clean up the message files so this is done explicitly instead of
// through this for-loop.
for (var messageKey in MSG) {
if (messageKey.indexOf("cat") == 0) {
Blockly.Msg[messageKey.toUpperCase()] = MSG[messageKey];
}
}
// Construct the toolbox XML, replacing translated variable names.
var toolboxText = document.getElementById("toolbox").outerHTML;
toolboxText = toolboxText.replace(/(^|[^%]){(\w+)}/g, function (m, p1, p2) {
return p1 + MSG[p2];
});
var toolboxXml = Blockly.Xml.textToDom(toolboxText);
Code.workspace = Blockly.inject("content_blocks", {
media: "blockly/media/",
rtl: rtl,
toolbox: toolboxXml,
zoom: {
controls: true,
wheel: true,
startScale: 1,
maxScale: 3,
minScale: 0.3,
scaleSpeed: 1.2,
},
collapse: true,
comments: false,
disable: true,
maxBlocks: Infinity,
trashcan: true,
horizontalLayout: false,
toolboxPosition: "start",
css: true,
scrollbars: true,
sounds: false,
theme: localStorage.getItem("darkmode") && THEME_DARKMODE(),
//oneBasedIndex: false
});
// Add to reserved word list: Local variables in execution environment (runJS)
// and the infinite loop detection function.
// Blockly.JavaScript.addReservedWords('code,timeouts,checkTimeout');
// var init_blocks_xml =
// Code.loadBlocks(init_blocks_xml);
// if ("BlocklyStorage" in window) {
// // Hook a save function onto unload.
// BlocklyStorage.backupOnUnload(Code.workspace);
// }
Code.simplify = function () {
let blocks_xml = Blockly.Xml.domToPrettyText(Blockly.Xml.workspaceToDom(Code.workspace));
//console.log(blocks_xml);
blocks_xml = blocks_xml.replace(/<shadow [^\n]*><\/shadow>/g, "");
//console.log(blocks_xml);
//Code.discard();
Code.workspace.clear();
var xml = Blockly.Xml.textToDom(blocks_xml);
Blockly.Xml.domToWorkspace(xml, Code.workspace);
//Code.renderContent();
};
Code.removeOwner = function () {
Code.device
.removeOwner()
.then(device => {
// @ts-ignore
window.alert("Mac " + device.mac + " removed", "Owner removed.");
})
.catch(e => {
// @ts-ignore
window.alert(e, "Failed to remove owner from the device.");
});
};
Code.fwVersion = function () {
Code.device
.getFwVersion()
.then(version => {
window.alert(version);
})
.catch(e => {
window.alert(e, "Failed get FW version");
});
};
Code.syncTngl = function () {
Code.device
.syncTngl(Blockly.Tngl.workspaceToCode(Code.workspace))
.then(() => {
window.alert("Tngl synchronized on the connected device");
})
.catch(e => {
window.alert(e, "Failed to sync tngl");
});
};
Code.deviceFingerprint = function () {
Code.device
.getTnglFingerprint()
.then(fingerprint => {
let digest = btoa(String.fromCharCode(...new Uint8Array(fingerprint)));
console.log(digest);
window.alert(digest);
})
.catch(e => {
window.alert(e, "Failed get TNGL fingerprint");
});
};
Code.blocklyFingerprint = function () {
var tngl_code = Blockly.Tngl.workspaceToCode(Code.workspace);
return computeTnglFingerprint(new TnglCodeParser().parseTnglCode(tngl_code), "fingerprint")
.then(fingerprint => {
let digest = btoa(String.fromCharCode(...new Uint8Array(fingerprint)));
console.log(digest);
window.alert(digest);
})
.catch(e => {
window.alert(e, "Failed get Blockly TNGL fingerprint");
});
};
Code.rebootDevice = function () {
Code.device.rebootDevice();
};
Code.rebootNetwork = function () {
Code.device.rebootNetwork();
};
document.getElementById("otaFirmware").addEventListener("change", async function () {
window.ota_uploadFrom = "file";
window.ota_firmware = await this.files[0]
.arrayBuffer()
.then(function (firmware) {
return firmware;
})
.catch(function (err) {
console.warn("Something went wrong.", err);
});
});
Code.otaUpdateDeviceFirmware = async function () {
if (window.ota_uploadFrom === "cloud") {
TangleMsgBox.alert(`Verze: ${fw_version_listDOM.value.replace(".enc", "")}`, "Probíhá stahování FW, uploadování se spustí po stažení FW.");
window.ota_firmware = await downloadSelectedFW();
}
console.log(window.ota_firmware);
return Code.device.updateDeviceFirmware(new Uint8Array(window.ota_firmware)).catch(e => {
console.error(e);
});
};
Code.otaUpdateNetworkFirmware = async function () {
if (window.ota_uploadFrom === "cloud") {
window.ota_firmware = await downloadSelectedFW();
TangleMsgBox.alert(`Verze: ${fw_version_listDOM.value.replace(".enc", "")}`, "Probíhá stahování FW, uploadování se spustí po stažení FW.");
}
console.log(window.ota_firmware);
return Code.device.updateNetworkFirmware(new Uint8Array(window.ota_firmware)).catch(e => {
console.error(e);
});
};
const config_textarea = document.querySelector("#config_textarea");
Code.otaReadDeviceConfig = function () {
Code.device
.readDeviceConfig()
.then(config => {
try {
const obj = JSON.parse(config);
const consif_pretty = JSON.stringify(obj, null, 2);
config_textarea.value = consif_pretty;
} catch {
config_textarea.value = config;
}
})
.then(() => {
window.alert("Config read SUCCESS");
})
.catch(e => {
//@ts-ignore
window.alert("Config read FAILED", e);
console.error(e);
});
};
Code.otaUpdateDeviceConfig = function () {
try {
const raw_config = config_textarea.value.replace(/\\"/g, '"');
console.log(raw_config);
const config_obj = JSON.parse(raw_config); // TODO - validate also json fields and it's datatypes
const config = JSON.stringify(config_obj);
return Code.device
.updateDeviceConfig(config)
.then(() => {
window.alert("Config write SUCCESS");
})
.catch(e => {
//@ts-ignore
window.alert("Config write FAILED", e);
console.error(e);
});
} catch (err) {
//@ts-ignore
window.alert("Something went wrong.", err);
}
};
Code.otaUpdateNetworkConfig = function () {
try {
const raw_config = config_textarea.value.replace(/\\"/g, '"');
console.log(raw_config);
const config_obj = JSON.parse(raw_config); // TODO - validate also json fields and it's datatypes
const config = JSON.stringify(config_obj);
return Code.device
.updateNetworkConfig(config)
.then(() => {
window.alert("Config write SUCCESS");
})
.catch(e => {
window.alert("Config write FAILED");
console.error(e);
});
} catch (err) {
//@ts-ignore
window.alert("Something went wrong.", err);
}
};
Code.tabClick(Code.selected);
Code.bindClick("simplifyButton", Code.simplify);
Code.bindClick("rebootDevice", Code.rebootDevice);
Code.bindClick("rebootNetwork", Code.rebootNetwork);
Code.bindClick("removeOwnerButton", Code.removeOwner);
Code.bindClick("fwVersionButton", Code.fwVersion);
Code.bindClick("syncTnglButton", Code.syncTngl);
Code.bindClick("deviceFingerprintButton", Code.deviceFingerprint);
Code.bindClick("blocklyFingerprintButton", Code.blocklyFingerprint);
Code.bindClick("otaUpdateDeviceFirmware", Code.otaUpdateDeviceFirmware);
Code.bindClick("otaUpdateNetworkFirmware", Code.otaUpdateNetworkFirmware);
Code.bindClick("otaReadDeviceConfig", Code.otaReadDeviceConfig);
Code.bindClick("otaUpdateDeviceConfig", Code.otaUpdateDeviceConfig);
Code.bindClick("otaUpdateNetworkConfig", Code.otaUpdateNetworkConfig);
Code.bindClick("connectSerialButton", Code.connectSerial);
Code.bindClick("connectBluetoothButton", Code.connectBluetooth);
Code.bindClick("adoptBluetoothButton", Code.adoptBluetooth);
Code.bindClick("uploadButton", Code.upload);
Code.bindClick("playButton", Code.play);