forked from chilipeppr/widget-template
-
Notifications
You must be signed in to change notification settings - Fork 9
/
widget.js
2326 lines (2185 loc) · 116 KB
/
widget.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
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
/* global $, cprequire_test, cpdefine, chilipeppr requirejs */
// Test this element. This code is auto-removed by the chilipeppr.load()
cprequire_test(["inline:com-chilipeppr-widget-grbl"], function(grbl) {
//console.log("test running of " + grbl.id);
grbl.init();
//testRecvline();
var sendGrblVersion = function() {
chilipeppr.publish("/com-chilipeppr-widget-serialport/recvline", {
dataline: "Grbl 0.8c"
});
};
chilipeppr.publish("/com-chilipeppr-widget-serialport/recvline", {
dataline: "$0=755.906 (x, step/mm)\n"
});
chilipeppr.publish("/com-chilipeppr-widget-serialport/recvline", {
dataline: "$1=755.906 (y, step/mm)\n"
});
chilipeppr.publish("/com-chilipeppr-widget-serialport/recvline", {
dataline: "$13=0 (report mode, 0=mm,1=inch)\n"
});
chilipeppr.publish("/com-chilipeppr-widget-serialport/recvline", {
dataline: "$3=30 (step pulse, usec)\n"
});
chilipeppr.publish("/com-chilipeppr-widget-serialport/recvline", {
dataline: "$5=500.000 (default feed, mm/min)\n"
});
chilipeppr.publish("/com-chilipeppr-widget-serialport/recvline", {
dataline: "[G0 G54 G17 G21 G90 G94 M0 M5 M9 T0 F500.0]\n"
});
chilipeppr.publish("/com-chilipeppr-widget-serialport/recvline", {
dataline: "[ALARM: Hard/soft limit]\n"
});
chilipeppr.publish("/com-chilipeppr-widget-serialport/recvline", {
dataline: "['$H'|'$X' to unlock]\n"
});
chilipeppr.publish("/com-chilipeppr-widget-3dviewer/unitsChanged", "inch");
chilipeppr.publish("/com-chilipeppr-widget-serialport/onQueue", {
Buf: 100
});
var sendTestPositionData = function() {
setTimeout(function() {
// MPos:[-0.05,0.00,0.00],WPos:[-0.05,0.00,0.00]
//chilipeppr.publish("/com-chilipeppr-widget-serialport/recvline", {
//dataline: "MPos:[-0.05,0.00,0.00],WPos:[-0.05,0.200,-1.00]" //0.8a
//dataline: "<idle,MPos:-0.05,0.00,0.00,WPos:-0.05,0.200,-1.00>" //0.8c
//
}, 2000);
};
sendGrblVersion();
sendTestPositionData();
chilipeppr.publish("/com-chilipeppr-widget-serialport/recvSingleSelectPort", {
BufferAlgorithm: "grbl"
}); //error not grbl buffer
} /*end_test*/ );
function Queue() {
var e = [];
var t = 0;
this.getLength = function() {
return e.length - t;
};
this.isEmpty = function() {
return e.length == 0;
};
this.enqueue = function(t) {
e.push(t);
};
this.dequeue = function() {
if (e.length == 0) return undefined;
var n = e[t];
if (++t * 2 >= e.length) {
e = e.slice(t);
t = 0;
}
return n;
};
this.peek = function() {
return e.length > 0 ? e[t] : undefined;
};
this.sum = function() {
for (var t = 0, n = 0; t < e.length; n += e[t++]);
return n;
};
this.last = function() {
return e[e.length - 1];
};
}
cpdefine("inline:com-chilipeppr-widget-grbl", ["chilipeppr_ready", "jquerycookie"], function() {
return {
probing: false,
id: "com-chilipeppr-widget-grbl",
implements: {
"com-chilipeppr-interface-cnccontroller": "The CNC Controller interface is a loosely defined set of publish/subscribe signals. The notion of an interface is taken from object-oriented programming like Java where an interface is defined and then specific implementations of the interface are created. For the sake of a Javascript mashup like what ChiliPeppr is, the interface is just a rule to follow to publish signals and subscribe to signals by different top-level names than the ID of the widget or element implementing the interface. Most widgets/elements will publish and subscribe on their own ID. In this widget we are publishing/subscribing on an interface name. If another controller like Grbl is defined by a member of the community beyond this widget for GRBL, this widget can be forked and used without other widgets needing to be changed and the user could pick a Grbl or GRBL implementation of the interface."
},
url: "(auto fill by runme.js)", // The final URL of the working widget as a single HTML file with CSS and Javascript inlined. You can let runme.js auto fill this if you are using Cloud9.
githuburl: "(auto fill by runme.js)", // The backing github repo
testurl: "(auto fill by runme.js)", // The standalone working widget so can view it working by itself
fiddleurl: "(auto fill by runme.js)",
name: "Widget / GRBL 1.1 compatibility test",
desc: "This widget shows the GRBL Buffer so other widgets can limit their flow of sending commands and other specific GRBL features.",
publish: {
'/com-chilipeppr-interface-cnccontroller/feedhold': "Feedhold (Emergency Stop). This signal is published when user hits the Feedhold button for an emergency stop of the GRBL. Other widgets should see this and stop sending all commands such that even when the plannerresume signal is received when the user clears the queue or cycle starts again, they have to manually start sending code again. So, for example, a Gcode sender widget should place a pause on the sending but allow user to unpause.",
'/com-chilipeppr-interface-cnccontroller/plannerpause': "This widget will publish this signal when it determines that the planner buffer is too full on the GRBL and all other elements/widgets need to stop sending data. You will be sent a /plannerresume when this widget determines you can start sending again. The GRBL has a buffer of 28 slots for data. You want to fill it up with around 12 commands to give the planner enough data to work on for optimizing velocities of movement. However, you can't overfill the GRBL or it will go nuts with buffer overflows. This signal helps you fire off your data and not worry about it, but simply pause the sending of the data when you see this signal. This signal does rely on the GRBL being in {qv:2} mode which means it will auto-send us a report on the planner every time it changes. This widget watches for those changes to generate the signal. The default setting is when we hit 12 remaining planner buffer slots we will publish this signal.",
'/com-chilipeppr-interface-cnccontroller/plannerresume': "This widget will send this signal when it is ok to send data to the GRBL again. This widget watches the {qr:[val]} status report from the GRBL to determine when the planner buffer has enough room in it to send more data. You may not always get a 1 to 1 /plannerresume for every /plannerpause sent because we will keep sending /plannerpause signals if we're below threshold, but once back above threshold we'll only send you one /plannerresume. The default setting is to send this signal when we get back to 16 available planner buffer slots.",
'/com-chilipeppr-interface-cnccontroller/axes': "This widget will normalize the GRBL status report of axis coordinates to send off to other widgets like the XYZ widget. The axes publish payload contains {x:float, y:float, z:float, a:float} If a different CNC controller is implemented, it should normalize the coordinate status reports like this model. The goal of this is to abstract away the specific controller implementation from generic CNC widgets.",
'/com-chilipeppr-interface-cnccontroller/units': "This widget will normalize the GRBL units to the interface object of units {units: \"mm\"} or {units: \"inch\"}. This signal will be published on load or when this widget detects a change in units so other widgets like the XYZ widget can display the units for the coordinates it is displaying.",
'/com-chilipeppr-interface-cnccontroller/proberesponse': 'Publish a probe response with the coordinates triggered during probing, or an alarm state if the probe does not contact a surface',
'/com-chilipeppr-interface-cnccontroller/status': 'Publish a signal each time the GRBL status changes',
'/com-chilipeppr-interface-cnccontroller/grblVersion': 'Publish the version number of the currently installed grbl',
"/com-chilipeppr-interface-cnccontroller/distance": 'publish whether we are in absolute or incremental mode',
'/com-chilipeppr-interface-cnccontroller/jogFeedRate': 'publish change in desired jog feed rate'
},
subscribe: {
'/com-chilipeppr-interface-cnccontroller/jogdone': 'We subscribe to a jogdone event so that we can fire off an exclamation point (!) to the GRBL to force it to drop all planner buffer items to stop the jog immediately.',
'/com-chilipeppr-interface-cnccontroller/recvgcode': 'Subscribe to receive gcode from other widgets for processing and passing on to serial port',
'/com-chilipeppr-interface-cnccontroller/coordinateUnits': 'Subscribe to units being sent by the gcode widget'
},
foreignPublish: {
"/com-chilipeppr-widget-serialport/send": "We send to the serial port certain commands like the initial configuration commands for the GRBL to be in the correct mode and to get initial statuses like planner buffers and XYZ coords. We also send the Emergency Stop and Resume of ! and ~"
},
foreignSubscribe: {
"/com-chilipeppr-widget-serialport/ws/onconnect": "When we see a new connect, query for status.",
"/com-chilipeppr-widget-serialport/recvline": "When we get a dataline from serialport, process it and fire off generic CNC controller signals to the /com-chilipeppr-interface-cnccontroller channel.",
"/com-chilipeppr-widget-serialport/send": "Subscribe to serial send and override so no other subscriptions receive command.",
"/com-chilipeppr-widget-grbl-autolevel/probing": "Subscribe to the autolevel widget to listen for probing commands",
"/com-chilipeppr-widget-serialport/onQueue": "we need to track whether someone is manually changing the config"
},
//plannerPauseAt: 128, // grbl planner buffer can handle 128 bytes of data
//qLength: new Queue(),
//qLine: new Queue(),
//g_count: 0,
//l_count: 0,
//interval_id: 0,
distance: '',
config: [],
err_log: [],
//config_index: [],
buffer_name: "",
report_mode: 0,
work_mode: 0,
controller_units: null,
status: "Offline",
version: "",
widgetVersion: '2017-09-03h',
q_count: 0,
alarm: false,
spindleSpeed: 'Off',
spindleDirection: 'CW',
feedRate: 0,
coolant: '-',
offsets: {
"x": 0.000,
"y": 0.000,
"z": 0.000
},
last_work: {
"x": 0.000,
"y": 0.000,
"z": 0.000
},
last_machine: {
"x": 0.000,
"y": 0.000,
"z": 0.000
},
g_status_reports: null,
gcode_lookup: {
"G0": "Rapid",
"G1": "Linear",
"G2": "Circular CW",
"G3": "Circular CCW",
"G38.2": "Probing",
"G80": "Cancel Mode",
"G54": "G54",
"G55": "G55",
"G56": "G56",
"G57": "G57",
"G58": "G58",
"G59": "G59",
"G17": "XY Plane",
"G18": "ZX Plane",
"G19": "YZ Plane",
"G90": "Absolute",
"G91": "Relative",
"G93": "Inverse",
"G94": "Units/Min",
"G20": "Inches",
"G21": "Millimetres",
"G43.1": "Active Tool Offset",
"G49": "No Tool Offset",
"M0": "Stop",
"M1": "Stop",
"M2": "End",
"M30": "End",
"M3": "Active-CW",
"M4": "Active-CCW",
"M5": "Off",
"M7": "Mist",
"M8": "Flood",
"M9": "Off"
},
//overrides stores the current state of the overrides
overrides: {
feedRate: 0,
rapids: 0,
spindleSpeed: 0
},
singleSelectPort: {}, // set up singleSelectPort
configFormatData: [{
"code": "0",
"setting": "Step pulse time",
"units": "microseconds",
"explanation": "Sets time length per step. Minimum 3usec.",
"tab": "Steps",
"fieldType": "integer",
"values": [],
"minimum": 3
}, {
"code": "1",
"setting": "Step idle delay",
"units": "milliseconds",
"explanation": "Sets a short hold delay when stopping to let dynamics settle before disabling steppers. Value 255 keeps motors enabled with no delay.",
"tab": "Steps",
"fieldType": "integer",
"values": [],
"maximum": 255,
"minimum": 0
}, {
"code": "2",
"setting": "Step pulse invert",
"units": "mask",
"explanation": "Inverts the step signal.",
"tab": "Inversions",
"fieldType": "axisMask",
"minimum": 0
}, {
"code": "3",
"setting": "Step direction invert",
"units": "mask",
"explanation": "Inverts the direction signal.",
"tab": "Inversions",
"fieldType": "axisMask",
"minimum": 0
}, {
"code": "4",
"setting": "Invert step enable pin",
"units": "boolean",
"explanation": "Inverts the stepper driver enable pin signal.",
"tab": "Inversions",
"fieldType": "switch",
"values": ["off", "on"],
"minimum": 0
}, {
"code": "5",
"setting": "Invert limit pins",
"units": "boolean",
"explanation": "Inverts the all of the limit input pins.",
"tab": "Inversions",
"fieldType": "switch",
"values": ["off", "on"],
"minimum": 0
}, {
"code": "6",
"setting": "Invert probe pin",
"units": "boolean",
"explanation": "Inverts the probe input pin signal.",
"tab": "Inversions",
"fieldType": "switch",
"values": ["off", "on"],
"minimum": 0
}, {
"code": "10",
"setting": "Status report options",
"units": "mask",
"explanation": "Alters data included in status reports.",
"tab": "Reporting",
"fieldType": "switch",
"values": ["standard", "full"],
"minimum": 0
}, {
"code": "11",
"setting": "Junction deviation",
"units": "millimeters",
"explanation": "Sets how fast Grbl travels through consecutive motions. Lower value slows it down.",
"tab": "Junction Deviation",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "12",
"setting": "Arc tolerance",
"units": "millimeters",
"explanation": "Sets the G2 and G3 arc tracing accuracy based on radial error. Beware: A very small value may effect performance.",
"tab": "Arc Tolerance",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "13",
"setting": "Report in inches",
"units": "boolean",
"explanation": "Enables inch units when returning any position and rate value that is not a settings value.",
"tab": "Reporting",
"fieldType": "switch",
"values": ["mm", "inch"],
"minimum": 0
}, {
"code": "20",
"setting": "Soft limits enable",
"units": "boolean",
"explanation": "Enables soft limits checks within machine travel and sets alarm when exceeded. Requires homing.",
"tab": "Limits",
"fieldType": "switch",
"values": ["off", "on"],
"minimum": 0
}, {
"code": "21",
"setting": "Hard limits enable",
"units": "boolean",
"explanation": "Enables hard limits. Immediately halts motion and throws an alarm when switch is triggered.",
"tab": "Limits",
"fieldType": "switch",
"values": ["off", "on"],
"minimum": 0
}, {
"code": "22",
"setting": "Homing cycle enable",
"units": "boolean",
"explanation": "Enables homing cycle. Requires limit switches on all axes.",
"tab": "Homing",
"fieldType": "switch",
"values": ["off", "on"],
"minimum": 0
}, {
"code": "23",
"setting": "Homing direction invert",
"units": "mask",
"explanation": "Homing searches for a switch in the positive direction. Set axis bit (00000ZYX) to search in negative direction.",
"tab": "Homing",
"fieldType": "axisMask",
"minimum": 0
}, {
"code": "24",
"setting": "Homing locate feed rate",
"units": "mm\/min",
"explanation": "Feed rate to slowly engage limit switch to determine its location accurately.",
"tab": "Homing",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "25",
"setting": "Homing search seek rate",
"units": "mm\/min",
"explanation": "Seek rate to quickly find the limit switch before the slower locating phase.",
"tab": "Homing",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "26",
"setting": "Homing switch debounce delay",
"units": "milliseconds",
"explanation": "Sets a short delay between phases of homing cycle to let a switch debounce.",
"tab": "Homing",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "27",
"setting": "Homing switch pull-off distance",
"units": "millimeters",
"explanation": "Retract distance after triggering switch to disengage it. Homing will fail if switch isn't cleared.",
"tab": "Homing",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "30",
"setting": "Maximum spindle speed",
"units": "RPM",
"explanation": "Maximum spindle speed. Sets PWM to 100% duty cycle.",
"tab": "Spindle",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "31",
"setting": "Minimum spindle speed",
"units": "RPM",
"explanation": "Minimum spindle speed. Sets PWM to 0.4% or lowest duty cycle.",
"tab": "Spindle",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "32",
"setting": "Laser-mode enable",
"units": "boolean",
"explanation": "Enables laser mode. Consecutive G1\/2\/3 commands will not halt when spindle speed is changed.",
"tab": "Laser",
"fieldType": "switch",
"values": ["off", "on"],
"minimum": 0
}, {
"code": "100",
"setting": "X-axis travel resolution",
"units": "step\/mm",
"explanation": "X-axis travel resolution in steps per millimeter.",
"tab": "Axis Resolution",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "101",
"setting": "Y-axis travel resolution",
"units": "step\/mm",
"explanation": "Y-axis travel resolution in steps per millimeter.",
"tab": "Axis Resolution",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "102",
"setting": "Z-axis travel resolution",
"units": "step\/mm",
"explanation": "Z-axis travel resolution in steps per millimeter.",
"tab": "Axis Resolution",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "110",
"setting": "X-axis maximum rate",
"units": "mm\/min",
"explanation": "X-axis maximum rate. Used as G0 rapid rate.",
"tab": "Axis FeedRate",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "111",
"setting": "Y-axis maximum rate",
"units": "mm\/min",
"explanation": "Y-axis maximum rate. Used as G0 rapid rate.",
"tab": "Axis FeedRate",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "112",
"setting": "Z-axis maximum rate",
"units": "mm\/min",
"explanation": "Z-axis maximum rate. Used as G0 rapid rate.",
"tab": "Axis FeedRate",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "120",
"setting": "X-axis acceleration",
"units": "mm\/sec^2",
"explanation": "X-axis acceleration. Used for motion planning to not exceed motor torque and lose steps.",
"tab": "Axis Acceleration",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "121",
"setting": "Y-axis acceleration",
"units": "mm\/sec^2",
"explanation": "Y-axis acceleration. Used for motion planning to not exceed motor torque and lose steps.",
"tab": "Axis Acceleration",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "122",
"setting": "Z-axis acceleration",
"units": "mm\/sec^2",
"explanation": "Z-axis acceleration. Used for motion planning to not exceed motor torque and lose steps.",
"tab": "Axis Acceleration",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "130",
"setting": "X-axis maximum travel",
"units": "millimeters",
"explanation": "Maximum X-axis travel distance from homing switch. Determines valid machine space for soft-limits and homing search distances.",
"tab": "Axis Max Travel",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "131",
"setting": "Y-axis maximum travel",
"units": "millimeters",
"explanation": "Maximum Y-axis travel distance from homing switch. Determines valid machine space for soft-limits and homing search distances.",
"tab": "Axis Max Travel",
"fieldType": "integer",
"values": [],
"minimum": 0
}, {
"code": "132",
"setting": "Z-axis maximum travel",
"units": "millimeters",
"explanation": "Maximum Z-axis travel distance from homing switch. Determines valid machine space for soft-limits and homing search distances.",
"tab": "Axis Max Travel",
"fieldType": "integer",
"values": [],
"minimum": 0
}],
isDebugMode: function() {
return $('.grbl-debug').hasClass('enabled');
},
grblConsole: function() {
if (this.isDebugMode()) {
if (arguments.length == 0) return;
/*if (arguments.length > 1) {
console.warn('grblConsole arguments' , arguments);
var a;
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] == 'object') {
a = a + ", " + JSON.stringify(arguments[i]);
}
else {
a = a + ", " + JSON.stringify(arguments[i]);
}
}
$('#com-chilipeppr-widget-grbl-debug-console').append(a + "\n");
}
else {
$('#com-chilipeppr-widget-grbl-debug-console').append(JSON.stringify(arguments[0]) + "\n");
}
*/
var mainArguments = Array.prototype.slice.call(arguments);
mainArguments.unshift('GRBL WIDGET: ');
console.info.apply(mainArguments);
}
},
findConfigItem: function(i) {
var rObj;
this.configFormatData.forEach(function(obj, index) {
if (obj.code == i) {
rObj = obj;
return true;
}
});
return rObj;
},
init: function() {
console.error('grbl: reference');
var query = window.location.search.substring(1);
var vars = query.split("&");
vars.forEach(function(item, index) {
var bits = item.split('=');
if (bits[0].toLowerCase() == 'debug' && bits[1] == 1) {
$('#com-chilipeppr-widget-grbl .grbl-debug').trigger('click');
}
}, this);
this.uiHover(); //set up the data elements for all UI
this.setupUiFromCookie();
this.btnSetup();
this.forkSetup();
$('#widgetVersion').text('(v. ' + this.widgetVersion + ')');
// setup recv pubsub event
// this is when we receive data in a per line format from the serial port
chilipeppr.subscribe("/com-chilipeppr-widget-serialport/recvline", this, function(msg) {
this.grblResponse(msg);
});
chilipeppr.subscribe("/com-chilipeppr-widget-serialport/onportopen", this, this.openController);
chilipeppr.subscribe("/com-chilipeppr-widget-serialport/onPortOpen", this, this.openController);
chilipeppr.subscribe("/com-chilipeppr-widget-serialport/onportclose", this, this.closeController);
// subscribe to jogdone so we can stop the planner buffer immediately
chilipeppr.subscribe("/com-chilipeppr-interface-cnccontroller/jogdone", this, function(msg) {
//chilipeppr.publish("/com-chilipeppr-widget-serialport/send", '!\n');
//this.sendCode('!\n');
setTimeout(function() {
chilipeppr.publish('/com-chilipeppr-interface-cnccontroller/plannerresume', "");
}, 2);
});
chilipeppr.subscribe("/com-chilipeppr-widget-serialport/recvSingleSelectPort", this, function(port) {
if (port !== null) {
this.singleSelectPort = port;
this.grblConsole("wsSend GOT PORT", this.singleSelectPort, port);
this.buffer_name = port.BufferAlgorithm;
if (this.buffer_name !== "grbl") {
$("#grbl-buffer-warning").show();
}
else {
$("#grbl-buffer-warning").hide();
}
}
});
//no longer following the send.
//chilipeppr.subscribe("/com-chilipeppr-widget-serialport/send", this, this.bufferPush, 1);
//listen for units changed
chilipeppr.subscribe("/com-chilipeppr-widget-3dviewer/unitsChanged", this, this.updateWorkUnits);
chilipeppr.subscribe("/com-chilipeppr-widget-3dviewer/recvUnits", this, this.updateWorkUnits);
chilipeppr.subscribe("/com-chilipeppr-interface-cnccontroller/units", this, this.updateWorkUnits); //this sets axes to match 3d viewer.
//listen for whether a gcode file is playing - if so, cancel our $G interval and start sending each 25 lines of gcode file sent.
chilipeppr.subscribe("/com-chilipeppr-widget-gcode/onplay", this, this.trackGcodeLines);
chilipeppr.subscribe("/com-chilipeppr-widget-gcode/onstop", this, this.restartStatusInterval);
chilipeppr.subscribe("/com-chilipeppr-widget-gcode/onpause", this, function(state, metadata) {
if (state === false) {
this.restartStatusInterval();
} //when gcode widget pauses, go back to interval querying $G
else if (state === true) {
this.trackGcodeLines();
} //when gcode widget resumes, begin tracking line count to embed $G into buffer.
});
chilipeppr.subscribe("/com-chilipeppr-widget-gcode/done", this, this.restartStatusInterval);
//call to determine the current serialport configuration
chilipeppr.publish("/com-chilipeppr-widget-serialport/requestSingleSelectPort", "");
//count spjs queue
chilipeppr.subscribe("/com-chilipeppr-widget-serialport/onWrite", this, function(data) {
if (data.QCnt >= 0) {
this.q_count = data.QCnt;
$('.stat-queue').html(this.q_count);
}
});
chilipeppr.subscribe("/com-chilipeppr-widget-serialport/onQueue", this, function(data){
if(/\$\d{1,3}\s*?=/.test(data.D)){
this.sendCode(String.fromCharCode(36) + String.fromCharCode(36) + '\n');
} else
if(/G20|G21/i.test(data.D)){
this.sendCode(String.fromCharCode(36) + "G\n");
}
});
//call to find out what current work units are
chilipeppr.publish("/com-chilipeppr-widget-3dviewer/requestUnits", "");
//watch for a 3d viewer /sceneReloaded and pass back axes info
chilipeppr.subscribe("/com-chilipeppr-widget-3dviewer/sceneReloaded", this, function(data) {
if (this.last_work.x !== null) {
this.publishAxisStatus(this.last_work);
}
else if (this.last_machine.x !== null) {
if (this.offsets.x !== null) {
['x', 'y', 'z'].forEach(function(f, index) {
this.last_work[f] = this.last_machine[f] - this.offsets[f];
}, this);
this.publishAxisStatus(this.last_work);
}
else {
this.publishAxisStatus(this.last_machine);
}
}
else {
this.publishAxisStatus({
"x": 0.000,
"y": 0.000,
"z": 0.000
});
}
});
chilipeppr.subscribe("/com-chilipeppr-widget-grbl-autolevel/probing", this, function(probing) {
this.probing = probing;
});
},
spindleEnabled: false,
spindleDirection: null,
coolant: "Off",
options: null,
isV1: function() {
return this.version.substring(0, 1) == '1' || $('#com-chilipeppr-widget-grbl .grbl-verbose').hasClass("enabled");
},
setVersion: function(ver) {
this.grblConsole('setting version to ' + ver);
if (ver !== "") {
var pattern = /([0-9.]+[a-z]?)/i;
var match = pattern.exec(ver);
ver = match[1] == undefined ? ver : match[1];
if (this.version != ver) {
this.version = ver;
$('#com-chilipeppr-widget-grbl .panel-title').text("GRBL (" + this.version + ")"); //update ui
chilipeppr.publish("/com-chilipeppr-interface-cnccontroller/grblVersion", this.version);
if (this.isV1() && this.config[10] != undefined && parseInt(this.config[10], 10) != 2) {
this.config[10] = 2;
this.commandQueue.push(String.fromCharCode(36) + "10=2\n");
this.doQueue();
}
}
}
else {
this.sendCode(String.fromCharCode(36) + "I\n");
}
},
setupUiFromCookie: function() {
// read vals from cookies
var options = $.cookie('com-chilipeppr-widget-grbl-options');
if (true && options) {
options = $.parseJSON(options);
//console.log("GRBL: just evaled options: ", options);
}
else {
options = {
showBody: true,
jogFeedRate: 200,
grblVersion: ""
};
}
if(options.grblVersion == 'undefined') options.grblVersion = "";
this.options = options;
this.version = this.options.grblVersion;
this.jogFeedRate = parseInt(this.options.jogFeedRate, 10);
if (isNaN(this.jogFeedRate)) this.jogFeedRate = 200;
this.setJogRate(this.jogFeedRate);
//console.log("GRBL: options:", options);
},
saveOptionsCookie: function() {
var options = {
showBody: this.options.showBody,
jogFeedRate: this.jogFeedRate,
grblVersion: this.version
};
var optionsStr = JSON.stringify(options);
//console.log("GRBL: saving options:", options, "json.stringify:", optionsStr);
// store cookie
$.cookie('com-chilipeppr-widget-grbl-options', optionsStr, {
expires: 365 * 10,
path: '/'
});
},
btnSetup: function() {
// chevron hide body
var that = this;
$('#com-chilipeppr-widget-grbl .hidebody').click(function(evt) {
var span = $(this).find('span');
if (span.hasClass('glyphicon-chevron-up')) { // panel-body is open, hide that
span.removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
$('#com-chilipeppr-widget-grbl .panel-body, #com-chilipeppr-widget-grbl .panel-footer').addClass('hidden');
}
else {
span.removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
$('#com-chilipeppr-widget-grbl .panel-body, #com-chilipeppr-widget-grbl .panel-footer').removeClass('hidden');
}
});
$('#com-chilipeppr-widget-grbl .grbl-feedhold').click(function() {
//console.log("GRBL: feedhold");
//alert($(this).data('command'));
var _cmd;
_cmd = $(this).data('command');
if(typeof _cmd == undefined) _cmd = '!';
that.sendCode(_cmd + " \n");
// announce to other widgets that user hit e-stop
if (_cmd == '!') {
chilipeppr.publish('/com-chilipeppr-interface-cnccontroller/plannerpause', "");
chilipeppr.publish("/com-chilipeppr-interface-cnccontroller/feedhold", "");
$(this).html("!");
$('#com-chilipeppr-widget-grbl .grbl-cyclestart').html('Resume').addClass("btn-success");
}
});
$('#com-chilipeppr-widget-grbl .grbl-cyclestart').click(function() {
//console.log("GRBL: cyclestart");
that.sendCode('~' + "\n");
//may want to check if buffer queue is >128 before resuming planner.
chilipeppr.publish('/com-chilipeppr-interface-cnccontroller/plannerresume', "");
$(this).html("~").removeClass("btn-success");
if (that.status != 'Jog') {
$('#com-chilipeppr-widget-grbl .grbl-feedhold').html('Hold !');
}
});
$('#com-chilipeppr-widget-grbl .grbl-verbose').click(function() {
//console.log("GRBL: manual status update");
$('#com-chilipeppr-widget-grbl .grbl-verbose').toggleClass("enabled");
});
$('#com-chilipeppr-widget-grbl .grbl-debug').click(function() {
if ($('.grbl-debug').hasClass("enabled")) {
$('#com-chilipeppr-widget-grbl-debug').hide();
$('.grbl-debug').removeClass("enabled");
}
else {
$('#com-chilipeppr-widget-grbl-debug').show()
$('.grbl-debug').addClass("enabled");
}
});
$('#com-chilipeppr-widget-grbl .grbl-v1mode').click(function() {
$('#com-chilipeppr-widget-grbl .grbl-v1mode').toggleClass("enabled");
});
$('#com-chilipeppr-widget-grbl .grbl-reset').click(function() {
//console.log("GRBL: reset");
that.sendCode(String.fromCharCode(24) + " \n");
chilipeppr.publish('/com-chilipeppr-interface-cnccontroller/plannerresume', "");
$('#com-chilipeppr-widget-grbl .grbl-cyclestart').html('~').removeClass("btn-success");
});
$('#com-chilipeppr-widget-grbl-btnoptions').click(this.showConfigModal.bind(this));
$('#com-chilipeppr-widget-grbl .btn-toolbar .btn, .com-chilipeppr-widget-grbl-realtime-commands .btn').popover({
delay: 500,
animation: true,
placement: "auto",
trigger: "hover",
container: 'body'
});
// new buttons start
// https://github.com/gnea/grbl/wiki/Grbl-v1.1-Commands
$('#com-chilipeppr-widget-grbl .grbl-safety-door').click(function() {
that.sendCode('\x84 ' + " \n");
});
$('#com-chilipeppr-widget-grbl .overrides-btn .btn').click(function() {
// send ascii code from data-send-code html tag
that.sendCode(String.fromCharCode(parseInt($(this).data("send-code"), 16)) + "\n");
});
$('#com-chilipeppr-widget-grbl .hide-overrides').click(function(evt) {
$(this).toggleClass("active");
$(".com-chilipeppr-widget-grbl-realtime-commands").toggle();
});
this.setJogRate(this.jogFeedRate);
// new buttons end
},
setJogRate: function(rate){
var jogFeedEditing = false;
this.jogFeedRate = rate;
var that= this;
$('.stat-jogFeedRate').text(this.jogFeedRate.toFixed(0))
.on('click', function(e) {
if (jogFeedEditing) return;
jogFeedEditing = true;
var val = $(this).text();
$(this).text('');
var node = $("<input>").val(val).css('width', '4rem')
.on('focusout', function() {
var val = $(this).val();
$('.stat-jogFeedRate').text(val);
jogFeedEditing = false;
var jFR = parseInt(val, 10);
chilipeppr.publish('/com-chilipeppr-interface-cnccontroller/jogFeedRate', jFR);
$(this).remove();
that.saveOptionsCookie();
})
.appendTo($(this));
});
chilipeppr.publish('/com-chilipeppr-interface-cnccontroller/jogFeedRate', parseInt(this.jogFeedRate, 10));
},
showConfigModal: function() {
if (!this.isConnected()) {
chilipeppr.publish("/com-chilipeppr-elem-flashmsg/flashmsg", "GRBL Widget", "The controller is not connected or offline");
return true;
}
this.config = [];
this.grblConsole("SJPS sending config request");
this.sendCode(String.fromCharCode(36) + String.fromCharCode(36) + "\n");
var interval = setInterval(function(context) {
var that = context;
if (that.config[0] == undefined) {
chilipeppr.publish("/com-chilipeppr-elem-flashmsg/flashmsg", "GRBL Widget", "Cannot load config from the controller.<br/>Is it properly connected?");
return false;
}
else {
clearInterval(interval);
}
$('#grbl-config-div').empty();
that.configFormatData.forEach(function(config_element, index_num) {
switch (config_element.fieldType) {
case 'switch':
var elem = $('\
<div class="input-group input-group-sm">\
<span class="input-group-addon">$' + config_element.code + '</span>\
<select class="form-control" data-index="' + config_element.code + '" id="com-chilipeppr-widget-grbl-config-' + config_element.code + '">\
<option value="0"></option>\
<option value="1"></option>\
</select>\
<span class="input-group-addon">' + config_element.setting + '</span>\
</div>');
$(elem).find('option').each(function(index, e) {
var v = parseInt($(this).val(), 10);
if (v == that.config[config_element.code][0]) {
$(this).prop('selected', 'selected');
}
$(this).text(config_element.values[v]);
});
break;
default:
var elem = $('\
<div class="input-group input-group-sm">\
<span class="input-group-addon">$' + config_element.code + '</span>\
<input class="form-control" data-index="' + config_element.code + '" id="com-chilipeppr-widget-grbl-config-' + config_element.code + '" value="' + that.config[config_element.code][0] + '"/>\
<span class="input-group-addon">' + config_element.setting + '</span>\
</div>');
}
//this should speed up the save event materially.
$(elem).on('blur', function(e, that) {
var val = $(this).val();
var index = $(this).data("index");
if (val != that.config[index][0]) {
var bits = val.split('.');
if (bits[1] && bits[1].length > 3) {
val = parseFloat(val).toFixed(3);
}
var cmd = String.fromCharCode(36) + index + "=" + val + "\n";
that.commandQueue.push(cmd);
that.doQueue();
that.config[index][0] = val;
}
}, that).appendTo('#grbl-config-div').popover({
title: String.fromCharCode(36) + config_element.code,
placement: 'bottom',
content: config_element.explanation,
trigger: 'hover'
});
}, that);
$('#grbl-config-div').append('<br/><button type="button" class="btn btn-sm btn-primary save-config">Save Settings To GRBL</button>');
$('.save-config').click(that.saveConfigModal.bind(that));
$('#com-chilipeppr-widget-grbl-modal').modal('show');
}, 1000, this);
},
hideConfigModal: function() {
$('#com-chilipeppr-widget-grbl-modal').modal('hide');
},
saveConfigModal: function() {
this.grblConsole("Save Settings");
var that = this;
$.each($("#grbl-config-div input"), function(k, inp) {
var val;
if ($(inp).data('skip') == true) return;
if ($(inp).is(':text')) {
val = $(inp).val();
}
else if ($(inp).is(':checkbox')) {
val = $(inp).is(':checked') ? 1 : 0;
}
var index = $(inp).data("index");
if (val != that.config[index][0]) {
that.assignConfigValue(index, val);
var bits = val.split('.');
var cmd = String.fromCharCode(36) + index + "=" + that.config[index][0] + "\n";
that.commandQueue.push(cmd);
}
});
// we need to re-send $$ ??
// that.commandQueue.push(String.fromCharCode(36) + String.fromCharCode(36) + "\n");
if (this.commandQueue.length == 0) {
this.hideConfigModal();
return true;
}
this.doQueue();
//changed this to hold the window in modal state until the config changes are made.
//it would probably be better to write each change on change of the input value rather than wait for a commit
//then the human interaction time would be greater than the eeprom delay and we'd not have this trouble.
var configInterval = setInterval(function(that) {
if (that.commandQueue.length == 0) {
that.hideConfigModal();
clearInterval(configInterval);
}
else {
chilipeppr.publish("/com-chilipeppr-elem-flashmsg/flashmsg", "GRBL Widget", "Please wait - saving new config");
that.doQueue();
}