-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSduino.js
More file actions
4933 lines (4680 loc) · 261 KB
/
JSduino.js
File metadata and controls
4933 lines (4680 loc) · 261 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
/*
"JSduino": Arduino en Javascript.
by: Juan José Guerra Haba (guerraTron). 4-01-2018. <[email protected]>
It Work within the "JSduino" namespace
and need the external libraries:
"raphael.js", "acorn.js + walk.js", "escodegen.js" and "edit_area.js"
in addition to the style scripts and the svg board
*/
/**
@namespace JSduino
@modules [ Code, core, effects, events, ino, objects, preload, raphael, SVG, ui, utils, Actuator, Pin ]
... for more details see file 'readme.md'
EXPLANATORY::
-------------
JSduino API modeled as 'web-app' for the construction and management of an 'Arduino' virtual system in the browser.
It is self-sufficient, it is responsible for all the construction of the interface and the logic, as well as the load
of the scripts necessary for its operation. Search for a resized optimum so that it occupies the maximum window.
The interface has been provided with the possibility of including some elements called 'actuators' (actuators, receivers,
indicators, ...), that allow us to give and receive values to the different pins of the board for an interaction
graphic that visually demonstrates the functioning of our code.
We have FOUR code representation windows, THREE where we will write code as we would in the IDE
Arduino (although at the moment only in 'javascript' language) even using the own Arduino functions, separated in
Global, Setup and Loop zones. Another is the output window of the console, which emulates just that, a Arduino console monitor.
The board is fully operational so that even its 'LEDs' indicate the real state of it at all times, as well
as the Reset button is interactive and produces the expected result.
OBSERVATIONS::
---------------
For purely visual reasons, the execution cycles of the written code have been slowed down INTENTIONALLY; for
side to allow the viewing of the results and on the other, it would be missing more, because the computer is infinitely faster
than any Arduino board.
Having said that, we must point out that this is an emulation with the purpose of facilitating development, not a final tool;
it is assumed that after testing our code we will pass to the real construction phase of the prototype with the Arduino IDE.
THANKS::
---------
It use the fantastic 'raphael.js' script for the construction of 'svg' and some effects. Thank you very much
to 'Dmitry Baranovskiy' (http://dmitry.baranovskiy.com/); which allows unprecedented compatibility
from: Firefox 3.0+, Safari 3.0+, Chrome 5.0+, Opera 9.5+ and Internet Explorer 6.0+.
Due to this we add another few kbts more but we gain in visual representation.
Also my thanks to the developers of the libraries 'acorn and escodegen' that allow to parse javascript code
allowing to create a manipulable AST.
And thanks to the API 'edit-area' with which I was able to show the code windows in a more 'friendly' way.
FEATURES:
----------------
- Programming with OOP philosophy. It has been developed by modules, although it has finally been mounted on a single file 'JSduino.js'
to facilitate loading.
- Use of namespaces and closures.
- Clean global scope. Only one global variable (jsvg) for accessing the object 'svg' and a single namespace: 'JSduino'
- Self-loading of necessary scripts. (js, css, svg, ...)
- Intelligent wait for the total load of the page. (timers, 'DOMContentLoaded', ...)
- Simulation of Arduino functions and features.
- Interactive interface with effects, sounds.
- Quasi-real Simulation
TROUBLESHOOTING::
------------------------------
//THERE MUST BE TIME FOR THE PARSER TO PROCESS AND LOAD THE JS FILE
//If we load the script '* .svg.raphael.js' with a normal label at the end of 'body' it would not give us problems, but
// when loading 'dynamically' in the 'init' function of 'JSduino' a pseudo-recharge is performed that prevents us from working properly
// inside the event 'DOMContentLoaded'.
// That's why everything that is trying to access the object 'jsvg' we need to slow it down with a 'timer'.
/*
setTimeout(function(){
var paper = jsvg;
//RESIZE THE RAPHAEL OBJECT:
paper.setSize("555", "432"); //raphael
paper.setViewBox(0, 0, 212, 162, true);//raphael
//JSduino.Raphael.scan();
}, 100);* /
All this has been resolved in a cross-browser way (almost, IE?), ignoring these calls because making them the API itself. But
even so it can present some anomalies in certain conditions and depending on the browser used.
If when opening it presents a problem, it is usually solved by refreshing the page.
SUMMARY::
---------
Call the API with the method 'init(..)', giving it some DOM element as a container, ... AND ENJOY THE MAGIC !!!
@see init(..) Main public method, it builds the interface
*/
var JSduino = (function (_JSduino_){
"use-strict";
//TIME CONSTANTS FOR TIMERS
var _TICKS_INTERVAL = 1000, _TICKS_INIT = 100, _TICKS_CLEAR = 100, _START_DELAY = 800; //msg.;
//MUTE SOUNDS
var _PLAY_SOUNDS_ = true;
var mute = !_PLAY_SOUNDS_;
//OBJECT DEFINING THE DEVICES TO BE USED
/* They are attributes of DOMElements objects that must correspond more or less faithfully with the constant
* defined in 'JSduino.Actuator' :: 'actuatorTypes', although the latter refer to javascript objects; where
* 'data' would correspond to 'name', and 'src' to 'imgs' more or less. */
var objectDevices = [
{
types: [],
modes: ["INPUT", "OUTPUT"],
attrs: {type: "li", data: "switcher", title: "Interruptor [INPUT]"},
children: [{attrs: {type: "img", src: "API/images/actuators/switcher_v_off.png", alt: "Interruptor"}}]
},
{
types: [],
modes: ["INPUT", "OUTPUT"],
attrs: {type: "li", data: "buttonNO", title: "Pulsador Normalmente Abierto (NO) [INPUT]"},
children: [{attrs: {type: "img", src: "API/images/actuators/button_v_off.png", alt: "Pulsador NO"}}]
},
{
types: [],
modes: ["INPUT", "OUTPUT"],
attrs: {type: "li", data: "buttonNC", title: "Pulsador Normalmente Cerrado (NC) [INPUT]"},
children: [{attrs: {type: "img", src: "API/images/actuators/button_v_on.png", alt: "Pulsador NC"}}]
},
{
types: [],
modes: ["INPUT", "OUTPUT"],
attrs: {type: "li", data: "sensor", title: "Dispositivo analógico, sensor, medidor, interruptor lineal, ... [INPUT]"},
children: [{attrs: {type: "img", src: "API/images/actuators/lineal_5.png", alt: "Sensor"}}]
},
{
types: [],
modes: ["INPUT", "OUTPUT"],
attrs: {type: "li", data: "led", title: "Dispositivo luminoso [OUTPUT]"},
children: [
{attrs: {type: "img", src: "API/images/actuators/led_red.png", alt: "led"}},
{
attrs: {type: "select", id: "deviceColor", alt: "Seleccionar el color del led"},
children: [
{attrs: {type: "option", value: "White", inner: "Blanco"}},
{attrs: {type: "option", value: "Red", inner: "Rojo"}},
{attrs: {type: "option", value: "Green", inner: "Verde"}},
{attrs: {type: "option", value: "Blue", inner: "Azul"}},
{attrs: {type: "option", value: "Orange", inner: "Naranja"}},
{attrs: {type: "option", value: "Yellow", inner: "Amarillo"}}
]
}
]
},
{
types: [],
modes: ["INPUT", "OUTPUT"],
attrs: {type: "li", data: "display", title: "Dispositivo Pantalla [OUTPUT]"},
children: [{attrs: {type: "img", src: "API/images/actuators/display_on.png", alt: "Display"}}]
}
];
var objectActuators = {};
//NAME OF THE JAVASCRIPT VARIABLE THAT TARGETS THE 'CANVAS-PAPER' OF THE RAPHAEL OBJECT THAT CONTAINS THE 'SVG'
var _PAPER_RAPHAEL_ = 'jsvg'; //It must be the same as the one defined in the object itself '*.svg.raphael.js'
var _ID_SVG_ = "contSVG"; //Id of the container. It must be the same as the one that appears on the object itself '*.svg.raphael.js'
//var scriptUTILS = 'API/js/UTILS.js';
var styleCSS = 'API/css/JSduino.css';
var scriptRaphael = 'js/raphaeljs/raphael.min.js';
var scriptSVGRaphael = "API/js/board/Arduino-VIII-SVGOMG.svg.raphael.js"; //ruta+nombre del script '*.svg.raphael.js";
//var modulePreload = 'API/js/modules/JSduino.preload.js';
var scriptAcorn = 'js/AST/acorn/acorn.es.browser.js';
var scriptWalk = 'js/AST/acorn/walk.es.browser.js';
var scriptEscodegen = 'js/AST/escodegen/escodegen.browser.min.js';
//var styleEditArea = 'js/editarea/edit_area.css';
var scriptEditArea = "js/editarea/edit_area_full.js";
/*var modulesArray = [ //CAN NOT BE USED, GIVES PROBLEMS FOR EXECUTION IN THE LOAD
//'../UTILS/UTILS.js',
//'API/js/raphaeljs/raphael.min.js',
//'API/js/modules/JSduino.js',
'API/js/modules/JSduino.preload.js',
'API/js/modules/JSduino.utils.js',
'API/js/modules/JSduino.ui.js',
'API/js/modules/JSduino.core.js',
'API/js/modules/JSduino.events.js',
'API/js/modules/JSduino.effects.js',
'API/js/modules/JSduino.raphael.js',
'API/js/modules/JSduino.SVG.js',
'API/js/modules/JSduino.Pin.js',
'API/js/modules/JSduino.Actuator.js'];*/
var raphael_groups = null; //Variable defined in the '*.svg.raphael.js' file
//VARs
var devices = []; //{"id": attrs.data, "name": attrs.data, "el": el} //[{"name": attrs.data, "el": el}, {...}, ...]
var deviceSel = null;
var actions = []; //[{"id": "runPause": "el": btnRunPause}, {...}, ...]
var actuators = []; //{id: id, act: new _JSduino_.Actuator(pin, typeDevice)}
var leds = [], ledders = [], glows = [];
var pines = []; //{id: id, pin: pin}
var pinsGroups = []; //{id: p, group: groups[p]}
var ledPower = null;
var JSduinoContainer = null, containerParent = null;
//CODE ZONES: GLOBAL, SETUP Y LOOP AT FIRST
var areas = ["Global", "Setup", "Loop"];
//var _PINS_CREATED_ = {};
//USED IN JSduino.ino::
/** Array of the pins configured through the 'pinMode' function, which are the ones enabled (in principle) for the code.
* Once the pin is configured in the 'setup' zone it should not be allowed to reconfigure in another part of the code,
* it will be must maintain the set start mode. */
var pinModeArray = [/*{id: 0, el: null, mode: null}*/];
//TIMERs
var timers = [];
var timeouts = [];
//LISTENERs
var listeners = [/*{el: DOMElement, eventType: 'click', handler: function_handler, bubble: true}*/];
var initied = {isInitied: false};
var btnLoad = null;
//STATICs INTERNAL FUNCTIONS
/** It obtains the data stored in the LI element (BUTTON-ACTUATOR).
* Normally an array with the value and status. (0 = select.value, 1 = HIGH | LOW)
* The VALUE indicates the pin number associated with the button, the STATE specifies if it is
* found in high or low state (HIGH | LOW)
* @param li [HTMLLiElement] The BUTTON-ACTUATOR from which to obtain the data.
* @return data [Array] An Array (extracted from the string format) with the stored data,
* where; data [0] = VALUE and data [1] = STATE. */
function getData(li){
return (li.data ? li.data.split(":") : null); //0 = select.value, 1= HIGH|LOW
}
/** It establishes the data to be stored in the LI element (BUTTON-ACTUATOR).
* It will be saved in the form of an array with text format, with the value and
* state. (0 = select.value, 1 = HIGH | LOW)
* The VALUE indicates the pin number associated with the button, the STATE specifies if it is
* found in high or low state (HIGH | LOW)
* @param li [HTMLLiElement] The BUTTON-ACTUATOR to which to add the data.
* @param value [String] The string that represents the associated pin number.
* @param state [String] A string representing the state: HIGH, LOW.
* @return data [String] A string (Array with string format) with the stored data. */
function setData(li, value, state){
li.data = (value + ":" + state);
return li.data;
}
function optionDisable(option, disable){
option.disabled = disable;
option.style.background = (disable ? "red" : "none");
}
function getContainer(){ return JSduinoContainer; }
/** It is used to load a previously saved configuration through the 'objectActuators' object that
* must have a very defined structure such that:
objectActuators =
{
INPUT:{ //UL ACTUATORS (INPUT, OUTPUT, LEVEL)
id: "buttonsInput",
caption: "INPUTS:<br />",
className: "actuators input",
list: [ //lis
{ //li actuator
type: "switcher", //switcher, pulse, button, buttonNO, buttonNC, sensor, led, ledWhite, ledRed, ...
family: "DIGITAL", //DIGITAL, ANALOG, POWER, AVR, SERIAL, SPI, I2C, PWM, INTERRUPT
id: "8", //"hole_8",
txt: "AC-DC",
value: 1,
className: "actuator"
},
{...}
]
},
...
}
*/
function reloadOldState(){
if(!_JSduino_.ui.containers.Root){ return null; }
var paper = _JSduino_.getPaper();
btnLoad = getGetSaved("chkLoad"); //_JSduino_.core.loadStore(2); //getGetSaved("btnLoad");
//We obtain the possible object 'objActuators' sent by post/get.
var objActuatorsSaved = btnLoad ? _JSduino_.core.loadStore(1) : null; //getPostSaved();
//We insert it in the general array
var objActuatorsAll = [objActuatorsSaved, objectActuators];
//We process them, in such a way that we give priority to the past through the init() method
for(var x=0; x<objActuatorsAll.length; x++){
var objAct = objActuatorsAll[x];
if(!objAct){ continue; }
for(var mode in objAct){
if(objAct.hasOwnProperty(mode)){
var obj = objAct[mode]; //obj.id, obj.caption, obj.className, obj.list
for(var i=0; i<obj.list.length; i++){ //list
var act = obj.list[i]; //act.id, act.type, act.mode, act.value, act.txt, act.className
deviceSel = act.type;
var pin = _JSduino_.utils.getPinCompatible(act.id, [mode]); //If there is any usable it is used
//If it is not found, a new one is created
pin = pin ? pin : new _JSduino_.Pin(act.id, mode, null, null, true); //strict mode
if(!pin || pin.error){
if(pin && pin.remove) { console.log("reloadOldState:: Borrado el pin temporal?... !" + (pin.remove() + "").toUpperCase() + "¡"); } //Suppresses it from the generic array
pin = null;
toC("ERROR en reloadOldState:: pin [" + act.id + "], Modo = '" + mode + "'. ¡ID o MODO erróneo!");
return null;
}
if(pin.mode !== mode) { pin.setMode(mode); }
pin.er.attr("fill", "white"); //IT SAYS IT AS ESTABLISHED
pin.setValue(0); //to reset value
if(!_JSduino_.ino.getPinModeArrayById(pin.id)){ pinModeArray.push({id: pin.id, el: pin, mode: pin.mode}); }
console.log("reloadOldState():: pin [" + pin.id + "] == '" + pin.pinDef.aka + "', setted to Mode = '" + pin.mode + "'");
//... end lines in pinMode.
if(pin){
var actNew = new _JSduino_.Actuator(pin, act.type);
if(actNew && actNew.pin && actNew.inputName && actNew.structure){
//pines.push({id: actNew.pin.id, pin: actNew.pin});
actNew.name = act.txt;
actNew.text = act.txt;
actNew.inputName.value = act.txt;
actNew.notify(act.value);
actNew.highlight(true);
//actuators.push({id: act.id, act: actNew}); //already the Actuator class does it
} else {
actNew.remove();
actNew = null;
//pin.remove();
pin = null;
}
}
}
}
}
}
}
/**/
function getGetSaved(name){
var cadVariables = location.search.substring(1,location.search.length); //delete ?
var arrVariables = cadVariables.split("&");
for (i=0; i<arrVariables.length; i++) {
var partes = arrVariables[i].split("=");
if(partes[0] == name){
//return JSON.parse(partes[1]);
return partes[1];
}
}
return null;
}
/** Sets the size of the canvas 'paper' SVG of JSduino.
* @param size {Object} Dimensions object for the 'paper' shown: {width: 360, height: 240, viewBox: {x: 0, y: 0, w: 260, h: 320}} */
function setSize(size){
size = size ? size : {}; //{width: 555, height:432, viewBox: {x:0, y:0, w:212, h:162}};
var defaultWidth = 283, defaultHeight = 202, paper = _JSduino_.getPaper();
if(!paper){ return null; }
var width = size.width ? size.width : paper.width;
width = width ? width : defaultWidth;
var height = size.height ? size.height : paper.height;
height = height ? height : defaultHeight;
var viewBox = size.viewBox ? size.viewBox : paper.viewBox;
//viewBox = viewBox ? viewBox : defaultViewBox;
if(!viewBox){ //"0 0 " + (svgWidth/1.3) + " " + (svgHeight/1.3);
viewBox = { x: 0, y: 0, w: (width/1.3), h: (height/1.3) };
}
//RESIZE THE RAPHAEL OBJECT:
paper.setSize(width*2, height*2); //raphael
paper.setViewBox(viewBox.x, viewBox.y, viewBox.w, viewBox.h, true);//raphael
}
function loadModules(pathArray, container, firstChild, attrs, callback ){
_JSduino_.utils.loadScript(pathArray.shift(), container, firstChild, attrs, callback);
if(pathArray.length > 0){ loadModules(pathArray, container, firstChild, attrs, callback ); }
}
function insertAfter(el, ref){
var sibling = ref.nextSibling;
var parent = ref.parentNode;
parent.insertBefore(el, sibling);
}
/** Main Method Startup and construction function of the entire JSduino system.
* Embed inside the event 'DOMContentLoaded'.
* @param container {DOMElement} [MANDATORY] DOM element container of the entire JSduino interface.
* @param size {Object} Dimensions object for the 'paper' shown: {x: 0, y: 0, w: 260, h: 320}
* @param objActuators {Object} Object with a very defined structure. (see 'objectActuators')*/
function init(container, size, objActuators){
//UTILS
//_JSduino_.utils.loadScript(scriptUTILS, null, true, {type: "text/javascript", async: true, defer: true}); //HEAD
//JSduino - CSS
_JSduino_.utils.loadStyle(styleCSS, null, true, {type: "text/css", rel: "stylesheet"}); //HEAD
//EDIT-AREA
_JSduino_.utils.loadScript(scriptEditArea, null, false, {type: "text/javascript", async: true, defer: true}); //HEAD
//RAPHAEL SVG
_JSduino_.utils.loadScript(scriptRaphael, document.body, false, {type: "text/javascript", async: true, defer: true}); //BODY
//_JSduino_.utils.loadScript(scriptSVGRaphael, document.body, false, {type: "text/javascript", async: true, defer: true}); //BODY
//ACORN
_JSduino_.utils.loadScript(scriptAcorn, null, false, {type: "text/javascript", async: true, defer: true}); //HEAD
//WALK
//_JSduino_.utils.loadScript(scriptWalk, null, false, {type: "text/javascript", async: true, defer: true}); //HEAD
//ESCODEGEN
_JSduino_.utils.loadScript(scriptEscodegen, null, false, {type: "text/javascript", async: true, defer: true}); //HEAD
_JSduino_.events.addEvent(null, null, function ready(){
//RAPHAEL SVG
//_JSduino_.utils.loadScript(scriptSVGRaphael, document.body, false, {type: "text/javascript", async: true, defer: true}); //BODY
var script = document.createElement("script");
script.src = scriptSVGRaphael;
script.type = "text/javascript";
insertAfter(script, container);
//UI
JSduinoContainer = containerParent = container;
container.appendChild(_JSduino_.ui.makeUI());
container.classList.add("containerSVG");
toDo(_JSduino_.raphael.scan, null , 80); //wait for the external script to load to incorporate its variable name raphael 'jsvg' (paper)
toDo(setSize, size, 100);
//if(objActuators) {
objectActuators = objActuators;
toDo(reloadOldState, null ,120);
//}
toDo(function(){ _JSduino_.core.init(true); }, null, 140);
//EDIT-AREA
toDo(function(){ _JSduino_.editArea = editAreaLoader; }, 160);
});
}
/** Encapsulates the function to be performed in a 'timeout' with a configurable wait time (default 100 msg.);
* Parameters can also be delivered to the function.
* <del>This method is the one that must be used outside of JSduino for code execution</del>, because it ensures a minimum time
* Waiting to allow the entire interface to be loaded. */
function toDo(paramFunction, params, millis){
setTimeout(paramFunction, (millis ? millis : 100), params);
}
function preSetup(param_func, params_others){
_JSduino_.core.preSetup(param_func, params_others);
}
function setup(param_func, params_others){
_JSduino_.core.setup(param_func, params_others);
}
function loop(param_func, params_others){
_JSduino_.core.loop(param_func, params_others);
}
//PUBLIC API:
Object.assign(_JSduino_,
{
_PAPER_RAPHAEL_: _PAPER_RAPHAEL_, //ACCESSIBLE CONSTANT FROM THE REST OF MODULES. It is the name of the variable that includes the Raphael object.
_ID_SVG_: _ID_SVG_, //ACCESSIBLE CONSTANT FROM THE REST OF MODULES. It is the id of the container that includes the Raphael object.
//RSVG: p_txt_mail,
//editArea: editAreaLoader, //NEED edit_area.js
getLogo: function(){ return _JSduino_.objects.images.logo; },
getImages: function(){ return _JSduino_.objects.images; },
getSounds: function(){ return _JSduino_.objects.sounds; },
getMusics: function(){ return _JSduino_.objects.musics; },
getMute: function(){ return mute; },
setMute: function(what){ mute = what; },
init: init, //Main entry point of the program.
toDo: toDo, //normal method to embed all the external HTML code to execute.
preSetup: preSetup,
setup: setup,
loop: loop,
V: function(){ return _JSduino_.core.V; },
A: function(){ return _JSduino_.core.A; },
objectDevices: objectDevices,
objectActuators: objectActuators,
deviceSel: deviceSel,
setSize: setSize,
getPaper: function(){ return _JSduino_.raphael.getPaper(); },
getContainer: getContainer,
getLedPower: function (){ return ledPower; },
getAreas: function(){ return areas; },
getCodeAreas: function(){ return _JSduino_.ui.containers.CodeAreas; },
getIcons: function(){ return _JSduino_.ui.icons; },
getActions: function (){ return actions; },
getDevices: function (){ return devices; },
getActuators: function (){ return actuators; },
getPines: function (){ return pines; },
getLeds: function (){ return leds; },
getPinsGroups: function (){ return pinsGroups; },
getGlows: function(){ return glows; },
getLedders: function (){ return ledders; },
getPinModeArray: function(){ return pinModeArray; },
getTimers: function(){ return timers; },
getTimeouts: function(){ return timeouts; },
getListeners: function(){ return listeners; },
getInitied: function(){ return initied; }
});
//BEGIN MODULE:: JSduino.utils
/** Sub-Namespace 'utils' inside the 'JSduino' namespace.
* Try different effects to apply to elements of both the
* graphical user interface as the 'core' itself, but that
* be 'Raphael-Objects' */
_JSduino_.utils = (function (){
//FROM UTILS.js
/** Load a 'style' link in the indicated Parent of the page, by default the HEAD.
* As attributes the route is allowed, the parent object where to insert it (HEAD, BODY, ...)
* whether to include it as the first child or not, an object of attributes, including a function of
* callback when finished loading. */
function loadStyle (href, parent, firstChild, attrs, nameCallback) {
if(!href) { return null; }
attrs = attrs || {};
parent = parent || document.getElementsByTagName("head")[0];
// Create element
var style = document.createElement("link");
// script attributes
for(var a in attrs){
if(attrs.hasOwnProperty(a)){
style.setAttribute(a, attrs[a]);
}
}
if(nameCallback) { style.onload = nameCallback; }
//if(nameCallback) { style.onload = "" + nameCallback + "()"; }
//if(nameCallback) { href = href + "?callback=" + nameCallback +"&onclick=" + nameCallback}
style.setAttribute("href", href);
if(firstChild){
parent.insertBefore(style, parent.firstChild);
} else {
parent.appendChild(style);
}
return true;
}
/** Load a script on the indicated Parent of the page, by default the HEAD.
* As attributes the route is allowed, the parent object where to insert it (HEAD, BODY, ...)
* whether to include it as the first child or not, an object of attributes, including a function of
* callback when finished loading.*/
function loadScript (src, parent, firstChild, attrs, nameCallback) {
if(!src) { return null; }
attrs = attrs || {};
parent = parent || document.getElementsByTagName("head")[0];
// Create element
var script = document.createElement("script");
// script attributes
for(var a in attrs){
if(attrs.hasOwnProperty(a)){
script.setAttribute(a, attrs[a]);
}
}
if(nameCallback) { script.onload = nameCallback; }
//if(nameCallback) { src = src + "?callback=" + nameCallback +"&onclick=" + nameCallback}
script.setAttribute("src", src);
if(firstChild){
parent.insertBefore(script, parent.firstChild);
} else {
parent.appendChild(script);
}
return true;
}
/** Create a script script online (not a file to load) in the indicated Parent of the page, by default the HEAD.
* As attributes the code in javascript is admitted, the parent object where to insert it (HEAD, BODY, ...)
* whether to include it as the first child or not, an object of attributes, including a function of
* callback when finished loading.*/
function createScript (code, parent, firstChild, attrs, nameCallback) {
if(!code) { return null; }
attrs = attrs || {};
parent = parent || document.getElementsByTagName("head")[0];
// Create element
var script = document.createElement("script");
// script attributes
for(var a in attrs){
if(attrs.hasOwnProperty(a)){
script.setAttribute(a, attrs[a]);
}
}
if(nameCallback) { script.onload = nameCallback; }
//if(nameCallback) { src = src + "?callback=" + nameCallback +"&onclick=" + nameCallback}
script.innerHTML = code;
if(firstChild){
parent.insertBefore(script, parent.firstChild);
} else {
parent.appendChild(script);
}
return true;
}
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}};
/**FROM MDM: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/max*/
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
/** Returns the index of the closest value in the array. The third parameter allows us to indicate if we want
* (in case of equality) the closest up, or down; default up. */
var getIndexFromNearest = function (value, arr, downUp) {
var result = Math.abs(getMaxOfArray(arr)-value); //máx
var index = -1;
for(var i=0; i<arr.length; i++){
var v = arr[i];
var dif = Math.abs(v-value);
var condicion = downUp ? (dif < result) : (dif <= result);
if(condicion){
result = Math.abs(v-value);
index = i;
}
}
return index;
};
/** FROM: MDM:: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/random
* INTEGER :: Returns a random integer between min (included) and max <del> (excluded) </del>. Using Math.round()
* will give you a non-uniform distribution! */
function getRandomInt(min, max) {
max += 0.0000000001; //Para que máx esté incluido
var max2 = Math.max(max, min);
var min2 = Math.min(max, min);
return Math.floor(Math.random() * (max2 - min2)) + min2;
}
/** Returns another array with the matching results in both input arrays, that is,
* calculates your BOOLEAN INTERSECTION.
* This method performs a BOOLEAN SETS operation, DOES NOT perform MATH OPERATIONS,
* since it treats arrays as sets with elements, not as mathematical values.
* Use 'indexOf' and the return value depends on what you can compare this javascript function. */
function arrIntersection(arr1, arr2){
var arrResult = [];
if(!arr1 || !arr2) { return arrResult; }
for(var i=0; i<arr1.length; i++){
if(arr2.indexOf(arr1[i]) > -1){ arrResult.push(arr1[i]); }
}
return arrResult;
}
/** Returns another array with the results NOT matching in both input arrays, that is,
* calculates your BOOLEAN DIFFERENTIATION.
* This method performs a BOOLEAN SETS operation, DOES NOT perform MATH OPERATIONS,
* since it treats arrays as sets with elements, not as mathematical values.
* Use 'indexOf' and the return value depends on what you can compare this javascript function. */
function arrDiferenciation(arr1, arr2){
var arrResult = [];
if(!arr1 || !arr2) { return arrResult; }
for(var i=0; i<arr1.length; i++){
if(arr2.indexOf(arr1[i]) == -1){ arrResult.push(arr1[i]); }
}
return arrResult;
}
/** Deletes duplicate elements in the array. It does not modify the delivered array, it returns a new array. */
function unique(arr){
return arr.filter(function (currentValue, index, array) {
//try{ return (arr.slice(index+1).indexOf(currentValue) < 0); }catch(e){ return true; }
if((index+1) < array.length) { return (array.slice(index+1).indexOf(currentValue) < 0); } else { return true; }
});
}
/** Just as the 'indexOf' method looks for matching values and returns the index, but between DOS ARRAYS. */
function indexOfArray(arr1, arr2){
var index = -1;
if(!arr1 || !arr2) { return index; }
arr1 = (arr1 instanceof Array) ? arr1 : [arr1];
arr2 = (arr2 instanceof Array) ? arr2 : [arr2];
for(var i=0; i<arr2.length; i++){
if(arr1.indexOf(arr2[i]) > -1){ return i;/*index = i;*/ }
}
return index;
}
/** Returns the main keys (keys) of an object. */
function objGetKeys(obj){
var keys = [];
for(var o in obj){
if(obj.hasOwnProperty(o)){
keys.push(o);
}
}
return keys;
}
//END UTILS.js
/** Utility function to clean the last name as a parameter to make it compatible with a name of
* javascript variable, eliminating spaces and other invalid characters. For example, it is useful for attributes
* 'id' of the elements that are subsequently translated into variable names or properties of objects. */
function availableVarName(id){ return id.replace(/[\.\s\*-]/gi, id); }
function getLedById(ledId){
for(var i=0; i<leds.length; i++){
var led = leds[i];
if(ledId == led.id) { return led.el; }
}
return null;
}
function getActionById(actionId){
for(var i=0; i<actions.length; i++){
var action = actions[i];
if(actionId == action.id) { return action.el; }
}
return null;
}
function getLedderById(ledderId){
for(var i=0; i<ledders.length; i++){
var ledder = ledders[i];
if(ledderId == ledder.id) { return ledder.ledder; }
}
return null;
}
function getDeviceById(deviceId){
for(var i=0; i<devices.length; i++){
var device = devices[i];
if(deviceId == devices.id) { return device.el; }
}
return null;
}
function getDeviceByData(deviceData){
for(var i=0; i<devices.length; i++){
var device = devices[i];
var el = device.el;
if(deviceData == el.getAttribute("data")) { return device; }
}
return null;
}
function getIndexActuatorById(actuatorId){
for(var i=0; i<actuators.length; i++){
var act = actuators[i];
if(actuatorId == act.id) { return i; }
}
return null;
}
function getIndexPinById(pinId){
for(var i=0; i<pines.length; i++){
var pin = pines[i];
if(pinId == pin.id) { return i; }
}
}
function getActuatorById(actuatorId){
for(var i=0; i<actuators.length; i++){
var act = actuators[i];
if(actuatorId == act.id) { return act.act; }
}
}
function getPinById(pinId){
for(var i=0; i<pines.length; i++){
var pin = pines[i];
if(pinId == pin.id) { return pin.pin; }
}
}
/** Useful in 'JSduino.ino', check if this pin id is already established,
* if so, return it, but return 'null'*/
function getPinUsed(id){
var pinModesArr = _JSduino_.getPinModeArray();
for(var i=0; i<pinModesArr.length; i++){
var pMode = pinModesArr[i];
if(id == pMode.id){
return pMode.el;
}
}
var pinActuators = _JSduino_.getActuators();
for(var i=0; i<pinActuators.length; i++){
var pAct = pinActuators[i].act;
if(id == pAct.pin.id){
return pAct.pin;
}
}
return null;
}
/** Useful in 'JSduino.ino', try to get a pin that is already established with that id,
* and that is compatible with any of the proposed modes; if so, it returns, but returns 'null'.
* First look at those already created (and compatible) by order in the 'pinModes' array and in the
* from 'actuators'*/
function getPinCompatible(id, modes){
//THE ARRAY 'pinModes' HAS PREFERENCE
var pin = _JSduino_.utils.getPinUsed(id);
//pin = pin ? (modes.indexOf(pin.mode) ? pin : null) : null;
//If it is already assigned to another actuator, use it
pin = _JSduino_.utils.getPinCompatibleWithActuatorsModes(pin);
//If the pin defined by 'pinMode' already exists, use it
pin = _JSduino_.utils.getPinCompatibleWithPinModes(pin, modes);
return pin;
}
function getPinCompatibleWithPinModes(pin, modes){
if(!pin) { return null; }
var pinCompatible = pin;
var pinModesArr = _JSduino_.getPinModeArray();
for(var i=0; i<pinModesArr.length; i++){
var pMode = pinModesArr[i];
if(pin.id == pMode.id){
if(modes.indexOf(pMode.mode) > -1){
pinCompatible = pMode.el;
break;
}
}
}
return pinCompatible;
}
function getPinCompatibleWithActuatorsModes(pin){
if(!pin) { return null; }
var pinCompatible = pin;
var pinActuators = _JSduino_.getActuators();
for(var i=0; i<pinActuators.length; i++){
var pAct = pinActuators[i].act;
if(pin.id == pAct.pin.id){
if(pAct.type.modes.indexOf(pin.mode) > -1){
pinCompatible = pAct.pin;
break;
}
}
}
return pinCompatible;
}
function cleanPines(){
var indexes = [];
for(var i=0; i<pines.length; i++){ if(!pines[i].pin){ indexes.push(i); } } //detecta los null
for(var i=0; i<indexes.length; i++){ pines.splice(indexes[i], 1); } //los suprime
}
/** Check if the 'id' of the SVGElement created by the 'pin' has an associated 'actuator' */
function hasActuator(id){
cleanActuators();
for(var i=0; i<actuators.length; i++){
if(id == actuators[i].id){
return i;
}
}
return false;
}
function cleanActuators(){
var indexes = [];
for(var i=0; i<actuators.length; i++){ if(!actuators[i].act){ indexes.push(i); } } //detecta los null
for(var i=0; i<indexes.length; i++){ actuators.splice(indexes[i], 1); } //los suprime
}
/** It makes an actuator object as a special saved object compatible with the 'objectActuators' type that
* must have a very defined structure such that:
objectActuators =
{
INPUT:{ //UL ACTUADORES (INPUT, OUTPUT, LEVEL)
id: "buttonsInput",
caption: "INPUTS:<br />",
className: "actuators input",
list: [ //lis
{ //li actuator
type: "switcher", //switcher, pulse, button, buttonNO, buttonNC, sensor, led, ledWhite, ledRed, ...
family: "DIGITAL", //DIGITAL, ANALOG, POWER, AVR, SERIAL, SPI, I2C, PWM, INTERRUPT
id: "8", //"hole_8",
txt: "AC-DC",
value: 1,
className: "actuator"
},
{...}
]
},
OUTPUT: ...
}
*/
function makeObjectActuators(actuators){
var inputs = { //Actuators
id: "buttonsInput",
caption: "ENTRADAS:<br />",
className: "actuators input",
list: []
};
var outputs = { //Receptors
id: "buttonsOutput",
caption: "SALIDAS:<br />",
className: "switches output",
list: []
};
var objActuators = {INPUT: inputs, OUTPUT: outputs};
for(var i=0; i<actuators.length; i++){
var act = actuators[i].act.toSaveObj();
var mod = objActuators[act.mode];
mod.list.push(act);
}
return objActuators;
}
//NOTIFICATIONS FOR OUTPUT PINS
function update(upd){
cleanActuators();
for(var i=0; i<actuators.length; i++){
actuators[i].act.notify(upd.value);
}
return false;
}
//var updater = document.getElementById("updater");
//updater.addEventListener("change", function (){ update(this); });
//COOKIES: FROM:
/** Try to save the information in cookies, if it could not be saved in 'localStorage' */
function setCookieStorage(cname, cvalue, exdays, path) {
//if(!cvalue){ return false; }
cname = cname || "JSduino_save";
exdays = exdays || 90;
path = path || "/";
try{
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
var cookieContent = (cname + "=" + utf82b64(cvalue) + ";" + expires + ";path=" + path); //max-age=<segundos>; domain=<dominio>; secure; httponly;
document.cookie = cookieContent;
//console.log(cname +"\n::\n" + cookieContent +"\n::\n" + document.cookie);
if(!document.cookie){ throw new Error("este navegador parece no admitir cookies"); }
} catch(e) {
//console.log("JSduino.utils.setCookie():: WARNING:: Algún problema al guardar los datos. Puede que las 'cookies' estén desactivadas: " + e);
console.log("...sin cookies... intentando guardar en almacenamiento local (localStorage)...");
return setLocalStorage(cname, cvalue);
}
return true;
}
/** Try to get the information of cookies, if it could not be tried of 'localStorage' */
function getCookieStorage(cname) {
//if(!hasCookie){ return false; }
var name = (cname || "JSduino_save") + "=";
try{
var decodedCookie = b642utf8(document.cookie); //decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
if(!decodedCookie){ throw new Error("quizás este navegador no admita cookies"); }
} catch(e) {
//console.log("WARNING:: Algún problema al obtener los datos. Puede que las 'cookies' estén desactivadas: " + e);
console.log("...sin cookies ... intentando acceder al contenido a través del almacenamiento local (localStorage)...");
return getLocalStorage(cname);
}
return null;
}
/** Check if there are cookies, if you can not check 'localStorage' */
function hasCookieStorage(cname) {
var name = getCookieStorage(cname || "JSduino_save");
//alert((name === false) + ":" + (name===""));
if ((name !== null) && (name !== false)) {
//console.log("COOKIE:: JSduino.save->" + name);
return true;
} else {
//console.log("WARNING:: Algún problema al preguntar por los datos. Puede que las 'cookies' estén desactivadas.");
console.log("...sin cookies ... intentando preguntar a través del almacenamiento local (localStorage)...");
name = getLocalStorage(cname);
return (name !== null) && (name !== "");
}
return false;
}
/** Try to delete the information of the cookies, if it could not be deleted from 'localStorage' */
function removeCookieStorage(cname, path) {
//if(!cvalue){ return false; }
cname = cname || "JSduino_save";
var maxAge = "max-age=0";
path = path || "/";
try{
var d = new Date();
d.setTime(d.getTime() - (1*24*60*60*1000)); //el día anterior
var expires = "expires="+ d.toUTCString();
var cookieContent = (cname + "=;" + expires + ";" + maxAge + ";path=" + path); //max-age=<segundos>; domain=<dominio>; secure; httponly;
document.cookie = cookieContent;
//console.log(cname +"\n::\n" + cookieContent +"\n::\n" + document.cookie);
if(!document.cookie){ throw new Error("este navegador parece no admitir cookies"); }
} catch(e) {
//console.log("JSduino.utils.setCookie():: WARNING:: Algún problema al guardar los datos. Puede que las 'cookies' estén desactivadas: " + e);
console.log("...sin cookies... intentando borrar desde el almacenamiento local (localStorage)...");
return removeLocalStorage(cname);
}
return true;
}
//LOCAL-STORAGE:
/** Save the information in 'localStorage' */
function setLocalStorage(sname, svalue){
//localStorage.setItem("lastname", "Smith"); //localStorage.getItem("lastname"); //localStorage.removeItem("lastname");
//if(!svalue){ return false; }
sname = sname || "JSduino_save";
if (typeof(Storage) !== "undefined") {
try{
// Code for localStorage/sessionStorage.
window.localStorage.setItem(sname, utf82b64(svalue));
}catch(e){
console.log("JSduino.utils->setLocalStorage():: Error en 'localStorage', probando con 'Storage.toString()' .. " + e);
svalue = window.Storage.toString(sname, utf82b64(svalue));
}
} else {
console.log("STORAGE:: Sorry! No Web Storage support..");
return false;
}
return true;
}
/** You will get the information of 'localStorage'. PROBLEMS WITH 'file: //' PROTOCOL */
function getLocalStorage(sname){
//localStorage.setItem("lastname", "Smith"); //localStorage.getItem("lastname"); //localStorage.removeItem("lastname");
//if(!svalue){ return false; }
sname = sname || "JSduino_save";
var svalue = "";
if (typeof(Storage) !== "undefined") {
try{
// Code for localStorage/sessionStorage.
svalue = b642utf8(window.localStorage.getItem(sname));
}catch(e){
console.log("JSduino.utils->getLocalStorage():: Error en 'localStorage', probando con 'Storage.valueOf()' .. " + e);
/*
//CAUSES A REDIRECTION:::
var l, p;
!localStorage && (l = location, p = l.pathname.replace(/(^..)(:)/, "$1$$"), (l.href = l.protocol + "//127.0.0.1" + p));*/
svalue = b642utf8(window.Storage.valueOf(sname));
}
} else {
console.log("STORAGE:: Sorry! No Web Storage support..");
return null;
}
return svalue;
}
/** Try to delete the last variable of the 'localStorage' */
function removeLocalStorage(sname){
//localStorage.setItem("lastname", "Smith"); //localStorage.getItem("lastname"); //localStorage.removeItem("lastname");
//if(!svalue){ return false; }