-
Notifications
You must be signed in to change notification settings - Fork 233
Expand file tree
/
Copy pathGeneral.ts
More file actions
1149 lines (1087 loc) · 36.6 KB
/
General.ts
File metadata and controls
1149 lines (1087 loc) · 36.6 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
import { CircuitElement } from './CircuitElement';
import { Point } from './Point';
import { areBoundingBoxesIntersecting } from './RaphaelUtils';
import _ from 'lodash';
import { Wire } from './Wire';
import { UndoUtils } from './UndoUtils';
import { isDragEnable } from '../simulator/simulator.component';
import { stopdrag } from '../simulator/simulator.component';
/**
* Declare window so that custom created function don't throw error
*/
declare var window;
/**
* Node tuple class to store breadboard node and element node which are in proximity
*/
class BreadboardProximityNodeTuple {
breadboardNode: Point;
elementNode: Point;
constructor(breadboardNode: Point, elementNode: Point) {
this.breadboardNode = breadboardNode;
this.elementNode = elementNode;
}
}
/**
* Resistor Class
*/
export class Resistor extends CircuitElement {
/**
* color table(hex values) of resistor
*/
static colorTable: string[] = [];
/**
* tolerance color mapping values of resistor
*/
static tolColorMap: number[] = [];
/**
* tolerance value of resistor
*/
static toleranceValues: string[] = [];
/**
* unit labels of resistor
*/
static unitLabels: string[] = [];
/**
* unit values of resistor
*/
static unitValues: number[] = [];
/**
* Resistance value of the resistor.
*/
value: number;
/**
* Tolerance index of the resistor.
*/
toleranceIndex: number;
/**
* flag for resistor :- if its value is default or imported from json .
*/
loadresistor: boolean;
/**
* Resistor constructor
* @param canvas Raphael Canvas (Paper)
* @param x position x
* @param y position y
*/
constructor(public canvas: any, x: number, y: number) {
super('Resistor', x, y, 'Resistor.json', canvas);
}
/** init is called when the component is completely drawn to the canvas */
init() {
if (Resistor.colorTable.length === 0) {
Resistor.colorTable = this.data.colorTable;
Resistor.toleranceValues = this.data.toleranceValues;
Resistor.tolColorMap = this.data.tolColorMap;
Resistor.unitLabels = this.data.unitLabels;
Resistor.unitValues = this.data.unitValues;
}
if (this.loadresistor === true) {
this.loadresistor = false;
} else {
this.value = this.data.initial;
this.toleranceIndex = this.data.initialToleranceIndex;
}
this.updateColors();
delete this.data;
this.data = null;
this.nodes[0].addValueListener((v, cby, par) => {
if (cby.parent.id !== this.id) {
this.nodes[1].setValue(v, this.nodes[0]);
}
});
this.nodes[1].addValueListener((v, cby, par) => {
if (cby.parent.id !== this.id) {
this.nodes[0].setValue(v, this.nodes[1]);
}
});
}
/** Saves data/values that are provided to resistor */
SaveData() {
return {
value: this.value,
tolerance: this.toleranceIndex
};
}
/**
* function loads the SaveData()
* @param data save object
*/
LoadData = (data: any) => {
this.value = data.data.value;
this.toleranceIndex = data.data.tolerance;
this.loadresistor = true;
}
/**
* Updates Resistor Properties
*/
updateColors() {
const cur = this.getValue();
this.elements[1].attr({
fill: Resistor.colorTable[cur.third]
}); // Third
this.elements[2].attr({
fill: Resistor.colorTable[cur.second]
}); // Second
this.elements[3].attr({
fill: Resistor.colorTable[cur.first]
}); // First
this.elements[5].attr({
fill: Resistor.colorTable[cur.multiplier]
}); // multiplier
this.elements[4].attr({
fill: Resistor.colorTable[this.toleranceIndex]
}); // Tolerance
}
/** Function gets Resistence value */
getValue() {
const l = `${this.value}`.length;
const tmp = `${this.value}`;
if (l < 2) {
return {
multiplier: 11,
first: this.value,
second: 0,
third: 0
};
} else if (l < 3) {
return {
multiplier: 10,
first: +tmp.charAt(0),
second: +tmp.charAt(1),
third: 0,
};
}
return {
multiplier: l - 3,
first: +tmp.charAt(0),
second: +tmp.charAt(1),
third: +tmp.charAt(2),
};
}
/** Power values for unitvalues 1K ohm => 10^3 */
private getPower(index: number) {
if (index >= 0 && index <= Resistor.unitValues.length) {
return Resistor.unitValues[index];
}
return 0;
}
/**
* Calculate the resistance based on the user input.
* @param value The Input resistance
* @param unitIndex The selected unit index
*/
update(value: string, unitIndex: number) {
const val = parseFloat(value);
const p = this.getPower(unitIndex);
const tmp = parseInt((val * p).toFixed(0), 10);
if (value.length > 12 || isNaN(tmp) || tmp === Infinity || tmp < 1.0 || `${tmp}`.length > 12) {
window['showToast']('Resistance Not possible');
return;
} else {
this.value = tmp;
this.updateColors();
}
}
/** Function returns resistence values 10K ohm => 10 */
getInputValues() {
const val = this.value;
let tmp = val;
for (let i = 0; i < Resistor.unitValues.length; ++i) {
tmp = Math.floor(val / Resistor.unitValues[i]);
if (tmp > 0) {
continue;
} else {
return {
index: i - 1,
val: val / Resistor.unitValues[i - 1]
};
}
}
return {
index: Resistor.unitValues.length - 1,
val: this.value / Resistor.unitValues[
Resistor.unitLabels.length - 1
]
};
}
/** Function returns the resistor with resistence */
getName() {
const cur = this.getInputValues();
return `Resistor ${cur.val}${Resistor.unitLabels[cur.index]}`;
}
/**
* Function provides component details
* @param keyName Unique Class name
* @param id Component id
* @param body body of property box
* @param title Component title
*/
properties(): { keyName: string; id: number; body: HTMLElement; title: string; } {
let tmp;
const cur = this.getInputValues();
const body = document.createElement('div');
const inp = document.createElement('input');
inp.type = 'number';
inp.value = `${cur.val}`;
inp.min = '1';
inp.addEventListener('wheel', (event) => {
event.preventDefault();
});
const unit = document.createElement('select');
tmp = '';
for (const ohm of Resistor.unitLabels) {
tmp += `<option>${ohm} Ω</option>`;
}
unit.innerHTML = tmp;
unit.selectedIndex = cur.index;
const tole = document.createElement('select');
tmp = '';
for (const t of Resistor.toleranceValues) {
tmp += `<option>± ${t}%</option>`;
}
tole.innerHTML = tmp;
unit.onchange = () => this.update(inp.value, unit.selectedIndex);
inp.onkeyup = () => this.update(inp.value, unit.selectedIndex);
inp.onchange = () => this.update(inp.value, unit.selectedIndex);
tole.onchange = () => {
this.toleranceIndex = Resistor.tolColorMap[tole.selectedIndex];
this.updateColors();
};
const lab = document.createElement('label');
lab.innerText = 'Resistance';
body.append(lab);
body.append(inp);
body.append(unit);
const lab2 = document.createElement('label');
lab2.innerText = 'Tolerance';
body.append(lab2);
body.append(tole);
return {
keyName: this.keyName,
id: this.id,
title: 'Resistor',
body
};
}
/**
* Called by the start simulation.
*/
initSimulation(): void {
}
/**
* Called by the stop simulation.
*/
closeSimulation(): void {
}
/**
* Get resistance value of resistor
*/
getResistance() {
return this.value;
}
/**
* Get ID of the resistor
* TODO: Add this function inside CircuitElements.ts instead
*/
getID() {
return this.id;
}
}
/**
* Breadboard Class
*/
export class BreadBoard extends CircuitElement {
/**
* Minimum distance of node to be classified as in proximity
*/
static PROXIMITY_DISTANCE = 20;
/**
* Set to keep track of visited nodes
*/
static visitedNodesv2 = new Set();
/**
* Stores group of points which are interconnected
*/
static groupings: any = [];
/**
* Nodes that are connected
*/
public joined: Point[] = [];
/**
* List to store current nodes in the proximity of any of the breadboard' node
*/
public highlightedPoints: BreadboardProximityNodeTuple[] = [];
/**
* Nodes sorted by 'x' and 'y' position
*/
public sortedNodes: Point[] = [];
/**
* Cached list of nodes that are soldered
*/
private solderedNodes: Point[] = null;
/**
* Map of x and nodes with x-coordinates as x
*/
public sameXNodes: { [key: string]: Point[] } = {};
/**
* Map of y and nodes with y-coordinates as y
*/
public sameYNodes: { [key: string]: Point[] } = {};
/**
* Breadboard constructor
* @param canvas Raphael Canvas (Paper)
* @param x position x
* @param y position y
*/
constructor(public canvas: any, x: number, y: number) {
super('BreadBoard', x, y, 'Breadboard.json', canvas);
this.subsribeToDrag({ id: this.id, fn: this.onOtherComponentDrag.bind(this) });
this.subscribeToDragStop({ id: this.id, fn: this.onOtherComponentDragStop.bind(this) });
}
/**
* Check if the breadboard is connected to any power components
* @returns powerrails which are powered
*/
static checkBreadboardPowerConnections() {
// console.log('Checking breadboard power rail connections...');
const poweredRails = new Set();
const pidGroups = {
plus1: new Set(Array.from({ length: 25 }, (index, n) => 1 + 4 * n)),
plus2: new Set(Array.from({ length: 25 }, (index, n) => 2 + 4 * n)),
minus1: new Set(Array.from({ length: 25 }, (index, n) => 4 * n)),
minus2: new Set(Array.from({ length: 25 }, (index, n) => 3 + 4 * n))
};
const checkConnections = (components = []) => {
for (const item of components) {
for (const { connectedTo } of item.nodes || []) {
if (!connectedTo) {
continue;
}
const { start, end } = connectedTo;
const startPid = start.id;
const endPid = end.id;
if (startPid != null || endPid != null) {
for (const [rail, pids] of Object.entries(pidGroups)) {
if (pids.has(startPid) && (start.label === '+' || start.label === '-')) {
poweredRails.add(rail);
// console.log(`Component ${item.keyName} connected to ${rail}`);
}
if (pids.has(endPid) && (end.label === '+' || end.label === '-')) {
poweredRails.add(rail);
// console.log(`Component ${item.keyName} connected to ${rail}`);
}
}
}
if (poweredRails.size === 4) {
return;
}
}
}
};
checkConnections([...window['scope'].ArduinoUno, ...window['scope'].Battery9v, ...window['scope'].CoinCell]);
// console.log('Checking breadboard reail to rail connections...');
for (const item of window['scope'].BreadBoard) {
for (const { connectedTo } of item.nodes || []) {
if (!connectedTo) {
continue;
}
const { start, end } = connectedTo;
if (!start || !end) {
continue;
}
const checkConnection = (pos, neg) => {
if (start.label === end.label &&
((pidGroups[pos].has(start.id) && pidGroups[neg].has(end.id)) ||
(pidGroups[neg].has(start.id) && pidGroups[pos].has(end.id)))) {
// console.log(`Wire connects ${pos} and ${neg}`);
if (poweredRails.has(pos)) {
poweredRails.add(neg);
}
if (poweredRails.has(neg)) {
poweredRails.add(pos);
}
}
};
for (const [pos, neg] of [['plus1', 'plus2'], ['minus1', 'minus2']]) {
checkConnection(pos, neg);
}
}
}
return { poweredRail: poweredRails.size ? Array.from(poweredRails) : null };
}
/**
* Check if all component pins are connected to the same powered rail (+ or -)
* @param poweredRail - List of powered rails
* @returns true if a short circuit is detected
*/
static checkAllPinsConnectedToOneRail(poweredRail) {
if (!poweredRail.length) {
// console.log('No powered rails detected.');
return false;
}
// console.log(`Powered rails detected: ${poweredRail.join(', ')}`);
const components = [
'Buzzer', 'LED', 'RGBLED', 'ServoMotor', 'Motor', 'PushButton',
'SlideSwitch', 'MQ2', 'PhotoResistor', 'PIRSensor', 'Potentiometer',
'TMP36', 'Thermistor', 'UltrasonicSensor', 'LCD16X2', 'Resistor'
]
.map(type => window['scope'][type])
.reduce((acc, val) => acc.concat(val), [])
.filter(Boolean);
if (!components.length) {
// console.log('No components found to check!');
return false;
}
for (const item of components) {
let allConnected = true;
for (const { connectedTo } of item.nodes || []) {
if (!connectedTo) {
allConnected = false;
break;
}
const { start, end } = connectedTo;
let rail = null;
if (start.label === '+') {
rail = start.id % 4 === 1 ? 'plus1' : 'plus2';
}
if (start.label === '-') {
rail = start.id % 4 === 0 ? 'minus1' : 'minus2';
}
if (end.label === '+') {
rail = end.id % 4 === 1 ? 'plus1' : 'plus2';
}
if (end.label === '-') {
rail = end.id % 4 === 0 ? 'minus1' : 'minus2';
}
// console.log(`Pin connected to: ${rail}`);
if (!rail || !poweredRail.includes(rail)) {
allConnected = false;
break;
}
}
if (allConnected) {
// console.log(`Component ${item.keyName} has all pins connected to a powered rail! Short circuit detected!`);
return true;
}
}
return false;
}
/**
* Returns node connected to arduino
* @param node node to start search on
* @param startedOn label of node search started on
* @returns Arduino connected Node
*/
static getRecArduinov2(node: Point, startedOn: string) {
try {
if (node.connectedTo.start.parent.keyName === 'ArduinoUno') {
// TODO: Return if arduino is connected to start node
return node.connectedTo.start;
} else if (node.connectedTo.end.parent.keyName === 'ArduinoUno') {
// TODO: Return if arduino is connected to end node
return node.connectedTo.end;
} else if (node.connectedTo.start.parent.keyName === 'BreadBoard' && !this.visitedNodesv2.has(node.connectedTo.start.gid)) {
// TODO: Call recursive BreadBoard handler function if node is connected to Breadboard && visited nodes doesn't have node's gid
return this.getRecArduinoBreadv2(node, startedOn);
} else if (node.connectedTo.end.parent.keyName === 'BreadBoard' && !this.visitedNodesv2.has(node.connectedTo.end.gid)) {
// TODO: Call recursive BreadBoard handler function if node is connected to Breadboard && visited nodes doesn't have node's gid
return this.getRecArduinoBreadv2(node, startedOn);
} else if (node.connectedTo.end.parent.keyName === 'Battery9v' && window.scope.ArduinoUno.length === 0) {
// TODO: Return false if node's end is connected to 9V Battery
return false;
} else if (node.connectedTo.end.parent.keyName === 'CoinCell' && window.scope.ArduinoUno.length === 0) {
// TODO: Return false if node's end is connected to Coin Cell
return false;
} else if (node.connectedTo.end.parent.keyName === 'RelayModule') {
// TODO: Handle RelayModule
if (startedOn === 'POSITIVE') {
// If search was started on Positive node then return connected node of VCC in Relay
return this.getRecArduinov2(node.connectedTo.end.parent.nodes[3], startedOn);
} else if (startedOn === 'NEGATIVE') {
// If search was started on Negative node then return connected node of GND in Relay
return this.getRecArduinov2(node.connectedTo.end.parent.nodes[5], startedOn);
}
} else {
// TODO: If nothing matches
// IF/ELSE: Determine if start is to be used OR end for further recursion
if (node.connectedTo.end.gid !== node.gid) {
// Loops through all nodes in parent
for (const e in node.connectedTo.end.parent.nodes) {
// IF: gid is different && gid not in visited node
if (node.connectedTo.end.parent.nodes[e].gid !== node.connectedTo.end.gid
&& !this.visitedNodesv2.has(node.connectedTo.end.parent.nodes[e].gid) && node.connectedTo.end.parent.nodes[e].isConnected()) {
// add gid in visited nodes
this.visitedNodesv2.add(node.connectedTo.end.parent.nodes[e].gid);
// call back Arduino Recursive Fn
return this.getRecArduinov2(node.connectedTo.end.parent.nodes[e], startedOn);
}
}
} else if (node.connectedTo.start.gid !== node.gid) {
// Loops through all nodes in parent
for (const e in node.connectedTo.start.parent.nodes) {
// IF: gid is different && gid not in visited node
if (node.connectedTo.start.parent.nodes[e].gid !== node.connectedTo.start.gid
&& !this.visitedNodesv2.has(node.connectedTo.start.parent.nodes[e].gid)
&& node.connectedTo.start.parent.nodes[e].isConnected()) {
// add gid in visited nodes
this.visitedNodesv2.add(node.connectedTo.start.parent.nodes[e].gid);
// call back Arduino Recursive Fn
return this.getRecArduinov2(node.connectedTo.start.parent.nodes[e], startedOn);
}
}
}
}
} catch (e) {
console.warn(e);
return false;
}
}
/**
* Recursive Function to handle BreadBoard
* @param node Node which is to be checked for BreadBoard
*/
static getRecArduinoBreadv2(node: Point, startedOn: string) {
// IF/ELSE: Determine if start is to be used OR end for further recursion
if (node.connectedTo.end.gid !== node.gid) {
const bb = (node.connectedTo.end.parent as BreadBoard);
// loop through joined nodes of breadboard
for (const e in bb.joined) {
if (bb.joined[e].gid !== node.connectedTo.end.gid) {
// Run only if substring matches
if (bb.joined[e].label.substring(1, bb.joined[e].label.length)
=== node.connectedTo.end.label.substring(1, node.connectedTo.end.label.length)) {
const ascii = node.connectedTo.end.label.charCodeAt(0);
const currAscii = bb.joined[e].label.charCodeAt(0);
// add gid to VisitedNode
this.visitedNodesv2.add(bb.joined[e].gid);
// IF/ELSE: determine which part of breadboard is connected
if (ascii >= 97 && ascii <= 101) {
if (bb.joined[e].isConnected() && (currAscii >= 97 && currAscii <= 101)) {
return this.getRecArduinov2(bb.joined[e], startedOn);
}
} else if (ascii >= 102 && ascii <= 106) {
if (bb.joined[e].isConnected() && (currAscii >= 102 && currAscii <= 106)) {
return this.getRecArduinov2(bb.joined[e], startedOn);
}
} else {
if (bb.joined[e].isConnected() && (bb.joined[e].label === node.connectedTo.end.label)) {
return this.getRecArduinov2(bb.joined[e], startedOn);
}
}
}
}
}
} else if (node.connectedTo.start.gid !== node.gid) {
const bb = (node.connectedTo.start.parent as BreadBoard);
// loop through joined nodes of breadboard
for (const e in bb.joined) {
if (bb.joined[e].gid !== node.connectedTo.start.gid) {
// Run only if substring matches
if (bb.joined[e].label.substring(1, bb.joined[e].label.length)
=== node.connectedTo.start.label.substring(1, node.connectedTo.start.label.length)) {
const ascii = node.connectedTo.start.label.charCodeAt(0);
const currAscii = bb.joined[e].label.charCodeAt(0);
// add gid to VisitedNode
this.visitedNodesv2.add(bb.joined[e].gid);
// IF/ELSE: determine which part of breadboard is connected
if (ascii >= 97 && ascii <= 101) {
if (bb.joined[e].isConnected() && (currAscii >= 97 && currAscii <= 101)) {
return this.getRecArduinov2(bb.joined[e], startedOn);
}
} else if (ascii >= 102 && ascii <= 106) {
if (bb.joined[e].isConnected() && (currAscii >= 102 && currAscii <= 106)) {
return this.getRecArduinov2(bb.joined[e], startedOn);
}
} else {
if (bb.joined[e].isConnected() && (bb.joined[e].label === node.connectedTo.end.label)) {
return this.getRecArduinov2(bb.joined[e], startedOn);
}
}
}
}
}
}
}
/**
* Subscribes to drag listener of the workspace
* @param fn listener functino
*/
subsribeToDrag(fn) {
// copied the function from Workspace here to avoid circular dependency. TODO: resolve file dependencies
window['DragListeners'].push(fn);
}
/**
* Subscribes to drag stop listener of the workspace
* @param fn listener function
*/
subscribeToDragStop(fn) {
window['DragStopListeners'].push(fn);
}
/**
* Resets highlighted points
*/
resetHighlightedPoints() {
if (this.highlightedPoints.length > 0) {
this.highlightedPoints.forEach(nodeTuple => nodeTuple.breadboardNode.undoHighlight());
this.highlightedPoints = [];
}
}
/**
* Returns list of soldered elements on the breadboard
*/
getSolderedElements() {
return this.getSolderedNodes().map(node => node.connectedTo);
}
/**
* Unsolders element from the breadboard if soldered
* @param element element to find and unsolder
*/
private maybeUnsolderElement(element) {
const elementNodesWires = element.nodes.map(node => node.connectedTo);
const solderedNodes = [...this.getSolderedNodes()];
for (const breadboardNode of solderedNodes) {
if (elementNodesWires.includes(breadboardNode.connectedTo)) {
breadboardNode.unsolderWire();
_.remove(this.solderedNodes, node => node === breadboardNode);
}
}
}
/**
* Listens for drag of other circuit elements in the workspace
*/
onOtherComponentDrag(element) {
const bBox = this.elements.getBBox();
const elementBBox = element.elements.getBBox();
// Disable Node Bubble on hover
Point.showBubbleBool = false;
this.resetHighlightedPoints();
if (!areBoundingBoxesIntersecting(bBox, elementBBox)) {
return;
}
// unsolder element if it's soldered to either of the breadboard's node
this.maybeUnsolderElement(element);
// for all the nodes of the elements, find the nodes in proximity to the nodes of the breadboard
// and add them to this.highlightedPoints
for (const node of element.nodes) {
if (node.isConnected()) {
continue;
}
const nearestNode = this.getNearestNodes(node.x, node.y);
if (nearestNode) {
this.highlightedPoints.push(new BreadboardProximityNodeTuple(nearestNode, node));
}
}
// highlight points stored in highlightedPoints
for (const node of this.highlightedPoints) {
node.breadboardNode.highlight();
}
}
/**
* Listener to handle when dragging of a component stops
*/
onOtherComponentDragStop() {
// Enable Node Bubble on hover
Point.showBubbleBool = true;
// if no highlighted points when the dragging stops, return
if (this.highlightedPoints.length === 0) {
return;
}
// connect highlightedPoints
for (const nodeTuple of this.highlightedPoints) {
const wire = nodeTuple.breadboardNode.solderWire();
wire.addPoint(nodeTuple.elementNode.x, nodeTuple.elementNode.y);
// wire.connect(nodeTuple.elementNode, true);
nodeTuple.elementNode.connectWire(wire, false);
this.addSolderedNode(nodeTuple.breadboardNode);
}
this.resetHighlightedPoints();
}
/** init is called when the component is complety drawn to the canvas */
init() {
this.sortedNodes = _.sortBy(this.nodes, ['x', 'y']);
if (BreadBoard.groupings.length === 0) {
BreadBoard.groupings = this.data.groupings;
}
// initialise sameX and sameY node sets
for (const node of this.nodes) {
// create the set for x
this.sameXNodes[node.x] = this.sameXNodes[node.x] || [];
this.sameXNodes[node.x].push(node);
// Create the set for y
this.sameYNodes[node.y] = this.sameYNodes[node.y] || [];
this.sameYNodes[node.y].push(node);
}
// add a connect callback listener
for (const node of this.nodes) {
node.connectCallback = (item) => {
this.joined.push(item);
};
node.disconnectCallback = (item) => {
const index = this.joined.indexOf(item);
if (index > -1) {
this.joined.splice(index, 1);
}
};
}
this.elements.toBack();
// Remove the drag event
this.elements.undrag();
let tmpx = 0;
let tmpy = 0;
let fdx = 0;
let fdy = 0;
let tmpar = [];
let tmpar2 = [];
let ConnEleList = [];
let NodeList = [];
let tmpx2 = [];
let tmpy2 = [];
// Create Custom Drag event
this.elements.drag((dx, dy) => {
if (isDragEnable.value === true) {
this.elements.transform(`t${this.tx + dx},${this.ty + dy}`);
tmpx = this.tx + dx;
tmpy = this.ty + dy;
fdx = dx;
fdy = dy;
for (let i = 0; i < this.joined.length; ++i) {
this.joined[i].move(tmpar[i][0] + dx, tmpar[i][1] + dy);
}
for (let i = 0; i < ConnEleList.length; ++i) {
ConnEleList[i].dragAlong(NodeList[i], dx, dy);
tmpx2[i] = ConnEleList[i].tx + dx;
tmpy2[i] = ConnEleList[i].ty + dy;
}
stopdrag.value = true;
}
}, () => {
if (isDragEnable.value === true) {
fdx = 0;
fdy = 0;
tmpar = [];
tmpar2 = [];
for (const node of this.nodes) {
tmpar2.push(
[node.x, node.y]
);
node.remainHidden();
}
for (const node of this.joined) {
let ElementFlag = false;
tmpar.push(
[node.x, node.y]
);
node.remainShow();
if (node.connectedTo != null) {
const ConnElement1 = node.connectedTo.start.parent;
const ConnElement2 = node.connectedTo.end.parent;
console.log(ConnElement1.keyName);
console.log(ConnElement2.keyName);
if (ConnElement1.keyName !== 'BreadBoard') {
for (const ele of ConnEleList) {
if (ele === ConnElement1) {
ElementFlag = true;
break;
}
}
const PlaceableCheck = 'isBreadBoardPlaceable' in ConnElement1.info.properties;
const isBreadBoardPlaceable = ConnElement1.info.properties.isBreadBoardPlaceable;
if (!ElementFlag && PlaceableCheck && isBreadBoardPlaceable === 1) {
ConnEleList.push(ConnElement1);
tmpx2.push(0);
tmpy2.push(0);
NodeList.push(ConnElement1.getNodesCoord());
}
} else {
for (const ele of ConnEleList) {
if (ele === ConnElement1) {
ElementFlag = true;
break;
}
}
const PlaceableCheck = 'isBreadBoardPlaceable' in ConnElement2.info.properties;
const isBreadBoardPlaceable = ConnElement2.info.properties.isBreadBoardPlaceable;
if (!ElementFlag && PlaceableCheck && isBreadBoardPlaceable === 1) {
ConnEleList.push(ConnElement2);
tmpx2.push(0);
tmpy2.push(0);
NodeList.push(ConnElement2.getNodesCoord());
}
}
}
}
}
}, () => {
// Push dump to Undo stack & Reset
if (isDragEnable.value === true) {
UndoUtils.pushChangeToUndoAndReset({ keyName: this.keyName, element: this.save(), event: 'drag', dragJson: { dx: fdx, dy: fdy } });
for (let i = 0; i < this.nodes.length; ++i) {
this.nodes[i].move(tmpar2[i][0] + fdx, tmpar2[i][1] + fdy);
this.nodes[i].remainShow();
}
tmpar2 = [];
this.tx = tmpx;
this.ty = tmpy;
// reBuild SameNodeObject after drag stop
if (stopdrag.value === true) {
for (let i = 0; i < ConnEleList.length; i++) {
ConnEleList[i].dragAlongStop(tmpx2[i], tmpy2[i]);
}
}
ConnEleList = [];
NodeList = [];
tmpx2 = [];
tmpy2 = [];
tmpar = [];
this.reBuildSameNodes();
stopdrag.value = false;
}
});
}
/**
* Function to move/transform breadboard
* @param fdx relative x position to move
* @param fdy relative y position to move
*/
transformBoardPosition(fdx: number, fdy: number): void {
if (isDragEnable.value === true && stopdrag.value === true) {
let tmpar = [];
let tmpar2 = [];
let tmpx = 0;
let tmpy = 0;
let ffdx = 0;
let ffdy = 0;
let ConnEleList = [];
let NodeList = [];
let tmpx2 = [];
let tmpy2 = [];
ffdx = 0;
ffdy = 0;
tmpar = [];
tmpar2 = [];
for (const node of this.nodes) {
tmpar2.push(
[node.x, node.y]
);
node.remainHidden();
}
for (const node of this.joined) {
tmpar.push(
[node.x, node.y]
);
node.remainShow();
const ConnElement1 = node.connectedTo.start.parent;
const ConnElement2 = node.connectedTo.end.parent;
console.log(ConnElement1.keyName);
console.log(ConnElement2.keyName);
let ElementFlag = false;
if (ConnElement1.keyName !== 'BreadBoard') {
for (const ele of ConnEleList) {
if (ele === ConnElement1) {
ElementFlag = true;
break;
}
}
if (!ElementFlag && ConnElement1.info.properties.isBreadBoardPlaceable === 1) {
ConnEleList.push(ConnElement1);
tmpx2.push(0);
tmpy2.push(0);
NodeList.push(ConnElement1.getNodesCoord());
}
} else {
for (const ele of ConnEleList) {
if (ele === ConnElement1) {
ElementFlag = true;
break;
}
}
if (!ElementFlag && ConnElement2.info.properties.isBreadBoardPlaceable === 1) {
ConnEleList.push(ConnElement2);
tmpx2.push(0);
tmpy2.push(0);
NodeList.push(ConnElement2.getNodesCoord());
}
}
}
this.elements.transform(`t${this.tx + fdx},${this.ty + fdy}`);
tmpx = this.tx + fdx;
tmpy = this.ty + fdy;
ffdx = fdx;
ffdy = fdy;
for (let i = 0; i < this.joined.length; ++i) {
this.joined[i].move(tmpar[i][0] + fdx, tmpar[i][1] + fdy);
}
for (let i = 0; i < ConnEleList.length; ++i) {
ConnEleList[i].dragAlong(NodeList[i], fdx, fdy);
tmpx2[i] = ConnEleList[i].tx + fdx;
tmpy2[i] = ConnEleList[i].ty + fdy;
}
for (let i = 0; i < this.nodes.length; ++i) {
this.nodes[i].move(tmpar2[i][0] + ffdx, tmpar2[i][1] + ffdy);
this.nodes[i].remainShow();
}
this.tx = tmpx;
this.ty = tmpy;
for (let i = 0; i < ConnEleList.length; i++) {
ConnEleList[i].dragAlongStop(tmpx2[i], tmpy2[i]);
}
ConnEleList = [];
NodeList = [];
tmpx2 = [];
tmpy2 = [];
tmpar = [];
this.reBuildSameNodes();
stopdrag.value = false;
}
}
/**
* Function provides component details
* @param keyName Unique Class name
* @param id Component id
* @param body body of property box
* @param title Component title
*/
properties(): { keyName: string; id: number; body: HTMLElement; title: string; } {
const body = document.createElement('div');
return {
keyName: this.keyName,
id: this.id,
body,
title: this.title