forked from chilipeppr/widget-spjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auto-generated-widget.html
3396 lines (3034 loc) · 184 KB
/
auto-generated-widget.html
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
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Widget / Serial Port JSON Server</title>
<!-- ChiliPeppr is based on bootstrap CSS. -->
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!-- Customized version of require.js for ChiliPeppr. Please see require.js docs for how
ChiliPeppr's dependency system works as it's based on require.js. -->
<script type='text/javascript' src="//i2dcui.appspot.com/js/require.js"></script>
<style type='text/css'>
.com-chilipeppr-widget-serialport .com-chilipeppr-widget-serialport-body {
padding:0;
overflow: auto;
overflow-x: hidden;
/* min-height:80px; */
}
.com-chilipeppr-widget-serialport .serial-port-version {
font-size:9px;
}
.com-chilipeppr-widget-serialport .panel-title {
font-size:12px;
}
.com-chilipeppr-widget-serialport-install .alert-warning {
/* max-height:130px; */
/* overflow: scroll; */
/* overflow-x: hidden; */
}
.com-chilipeppr-widget-serialport .com-chilipeppr-widget-serialport-body .row .col-xs-12 {
padding:0;
}
.com-chilipeppr-widget-serialport .table {
margin-bottom:0;
}
.com-chilipeppr-widget-serialport-disconnected {
position: absolute;
width: 100%;
background-color: rgba(0,0,0,0.7);
color: white;
height:80%;
text-align: center;
vertical-align: middle;
display: table-cell;
line-height: 100%;
z-index: 100;
margin:0;
padding:20px;
/* min-height:50px; */
}
.com-chilipeppr-widget-serialport .com-chilipeppr-widget-serialport-status .well.well-sm {
margin: 0;
padding-left:16px;
font-size: 10px;
}
.com-chilipeppr-widget-serialport .btn .glyphicon-ok-circle {
padding: 0 16px;
}
.com-chilipeppr-widget-serialport .com-chilipeppr-widget-serialport-console {
padding-top: 0px;
}
.com-chilipeppr-widget-serialport .com-chilipeppr-widget-serialport-console-log {
overflow: auto;
height: 160px;
margin:0;
padding: 0 8px;
}
.com-chilipeppr-widget-serialport .panel-footer {
font-size: 11px;
}
.com-chilipeppr-widget-serialport-portlist {
margin-bottom:0;
}
.com-chilipeppr-widget-serialport-portlistarea {
max-height:150px;
overflow: auto;
}
.com-chilipeppr-widget-serialport input[type=checkbox] {
margin-left:10px;
}
.com-chilipeppr-widget-serialport .com-chilipeppr-widget-serialport-baud {
/* margin-right:10px; */
font-size:12px;
margin:0 0 2px 0;
width:85px;
}
.com-chilipeppr-widget-serialport-index {
list-style-type: none;
padding-left: 0;
}
.com-chilipeppr-widget-serialport-install {
max-height:300px;
overflow:auto;
}
.com-chilipeppr-widget-serialport-install p {
padding-top:10px;
}
.com-chilipeppr-widget-serialport-install p:first {
padding-top:0px;
}
.com-chilipeppr-widget-serialport .panel-heading .title {
line-height: 12px;
}
.com-chilipeppr-widget-serialport .panel-heading .subtitle {
font-size:10px;
display:inline;
}
.com-chilipeppr-widget-serialport .panel-heading .hosttitle {
font-size:10px;
display:inline;
}
.com-chilipeppr-widget-serialport .out {
color: blue;
}
.com-chilipeppr-widget-serialport-console-log pre {
margin:0;
padding:0;
border:none;
}
.com-chilipeppr-widget-serialport-buffer {
font-size:12px;
width:85px;
/* margin-bottom:2px; */
}
.com-chilipeppr-widget-serialport-progbar {
width:85px;
}
.com-chilipeppr-widget-serialport-body .nav-tabs {
margin-left: -15px;
margin-right: -15px;
margin-top: 3px;
padding-left: 10px;
}
.com-chilipeppr-widget-serialport-body .nav>li>a {
padding: 2px 7px;
}
.com-chilipeppr-widget-serialport-img {
border: 0px solid red;
border-radius: 5px;
position: relative;
width: 50%;
height: 100px;
background-position: center;
background-size: cover;
}
.com-chilipeppr-widget-serialport-body .cloud-card {
/* margin-bottom:4px; */
/* margin-top:4px; */
margin-right:-10px;
border-spacing: 2px;
/* border-color: gray; */
border-bottom: 1px solid #ddd;
cursor: pointer;
}
.com-chilipeppr-widget-serialport-body .cloud-card:hover {
background-color: #f5f5f5;
}
.com-chilipeppr-widget-serialport-body .cloud-card:active {
background-color: #ddd;
}
.com-chilipeppr-widget-serialport-body .cloud-card a {
font-size:10px;
/* word-wrap: break-word; */
/* word-break: break-all; */
line-height:10px;
}
.com-chilipeppr-widget-serialport-body .cloud-card h4 {
margin-bottom:0;
font-size:15px;
line-height: 15px;
}
.com-chilipeppr-widget-serialport-body .cloud-card p {
font-size:10px;
margin-bottom:0;
}
.com-chilipeppr-widget-serialport .progress {
margin:0;
}
.com-chilipeppr-widget-serialport .deviceimg {
cursor:pointer;
width:80px;
border-radius:6px;
margin:6px 3px;
}
.com-chilipeppr-widget-serialport .deviceImgTd {
padding:0;
}
.btn.com-chilipeppr-serialport-setDefaultBtn {
font-size: 9px;
height: 16px;
}
.lastModifyDate {
color:silver;
}
.script-code {
border: 0;
font-size: 9px;
margin: 0;
padding: 0;
background-color: transparent;
}
#com-chilipeppr-serialport-modalconfig .recent-file-item {
cursor:pointer;
}
</style>
<script type='text/javascript'>
//<![CDATA[
/* global requirejs cprequire cpdefine chilipeppr */
// Defining the globals above helps Cloud9 not show warnings for those variables
// ChiliPeppr Widget/Element Javascript
requirejs.config({
/*
Dependencies can be defined here. ChiliPeppr uses require.js so
please refer to http://requirejs.org/docs/api.html for info.
Most widgets will not need to define Javascript dependencies.
Make sure all URLs are https and http accessible. Try to use URLs
that start with // rather than http:// or https:// so they simply
use whatever method the main page uses.
Also, please make sure you are not loading dependencies from different
URLs that other widgets may already load like jquery, bootstrap,
three.js, etc.
You may slingshot content through ChiliPeppr's proxy URL if you desire
to enable SSL for non-SSL URL's. ChiliPeppr's SSL URL is
https://i2dcui.appspot.com which is the SSL equivalent for
http://chilipeppr.com
*/
paths: {
// Example of how to define the key (you make up the key) and the URL
// Make sure you DO NOT put the .js at the end of the URL
// SmoothieCharts: '//smoothiecharts.org/smoothie',
},
shim: {
// See require.js docs for how to define dependencies that
// should be loaded before your script/widget.
}
});
// Test this element. This code is auto-removed by the chilipeppr.load()
cprequire_test(["inline:com-chilipeppr-widget-serialport"], function (sp) {
console.log("test running of " + sp.id);
$('body').css("padding", "20px");
//sp.init("192.168.1.7");
/*
sp.setSingleSelectMode();
sp.init(null, "tinyg", 115200, "tinyg (or if you are using the Arduino Due or v9 board choose tinygg2)");
//sp.init(null, "grbl");
*/
sp.init({
isSingleSelectMode: true,
defaultBuffer: "nodemcu",
defaultBaud: 9600,
bufferEncouragementMsg: 'For your NodeMCU device please choose the "timed" buffer in the pulldown and a 9600 baud rate before connecting.'
});
sp.consoleToggle();
var test = function() {
setTimeout(function() {
for (ctr = 0; ctr < 3; ctr++) {
//sp.sendBuffered('{"sr":""}\n');
//sp.sendBuffered('{"qr":""}\n');
sp.sendBuffered('{"sr":""}\n{"qr":""}\n');
}
}, 5000);
}
//test()
var test2 = function() {
for (ctr = 0; ctr < 30; ctr++) {
setTimeout(function() {
sp.sendBuffered('{"sr":""}\n');
sp.sendBuffered('{"qr":""}\n');
}, 5000 + (ctr * 2));
}
}
//test2()
setTimeout(function() {
chilipeppr.publish("/com-chilipeppr-widget-serialport/requestSingleSelectPort", "");
}, 2000);
/*
setTimeout(function() {
chilipeppr.publish("/" + sp.id + "/send", '{"sr":""}\n{"sr":""}\n{"sr":""}\n{"sr":""}\n');
//chilipeppr.publish("/" + sp.id + "/ws/send", 'send COM22 {"sr":""}\nsend COM22 {"sr":""}\nsend COM22 {"sr":""}\nsend COM22 {"sr":""}\n');
}, 2000);
setTimeout(function() {
// chilipeppr.publish("/" + sp.id + "/ws/send", 'send COM22 {"sr":""}\n');
}, 1000);
*/
//sp.wsScan();
var testProgrammer = function() {
var testProgrammerDiv = $("<div></div>").attr("id", "com-chilipeppr-widget-programmer-div");
$('#com-chilipeppr-widget-serialport').append(testProgrammerDiv);
// Programmer
// FIDDLE http://jsfiddle.net/chilipeppr/qcduvhkh/11/
chilipeppr.load(
"com-chilipeppr-widget-programmer-div",
"http://fiddle.jshell.net/chilipeppr/qcduvhkh/show/light/"
);
}
testProgrammer();
var testFro = function() {
setTimeout(function() {
chilipeppr.publish("/com-chilipeppr-widget-serialport/requestFro", "3.5");
}, 3000);
}
testFro();
var testStatus = function() {
setTimeout(function() {
chilipeppr.publish("/com-chilipeppr-widget-serialport/requestStatus", "3.5");
}, 6000);
}
testStatus();
// we need to also load the serial port console to make sure they are synced
// Inject new div to contain widget or use an existing div with an ID
$("body").append('<' + 'div id="myDivWidgetSpconsole"><' + '/div>');
chilipeppr.load(
"#myDivWidgetSpconsole",
"http://raw.githubusercontent.com/chilipeppr/widget-console/master/auto-generated-widget.html",
// "http://widget-console-chilipeppr.c9users.io/widget.html",
function() {
// Callback after widget loaded into #myDivWidgetSpconsole
// Now use require.js to get reference to instantiated widget
cprequire(
["inline:com-chilipeppr-widget-spconsole"], // the id you gave your widget
function(myObjWidgetSpconsole) {
// Callback that is passed reference to the newly loaded widget
console.log("Widget / Serial Port Console v1.7 just got loaded.", myObjWidgetSpconsole);
myObjWidgetSpconsole.init(true);
}
);
}
);
} /*end_test*/ );
cpdefine("inline:com-chilipeppr-widget-serialport", ["chilipeppr_ready", "jquerycookie"], function () {
return {
id: "com-chilipeppr-widget-serialport",
name: "Widget / Serial Port JSON Server",
desc: "The essential widget if you want your workspace to talk to the Serial Port JSON Server (SPJS). This widget enables numerous pubsub signals so you can publish to SPJS and receive data back when you subscribe to the appropriate signals.",
url: "http://raw.githubusercontent.com/chilipeppr/widget-spjs/master/auto-generated-widget.html", // 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.
fiddleurl: "http://ide.c9.io/chilipeppr/widget-spjs", // The edit URL. This can be auto-filled by runme.js in Cloud9 if you'd like, or just define it on your own to help people know where they can edit/fork your widget
githuburl: "http://github.com/chilipeppr/widget-spjs", // The backing github repo
testurl: "http://widget-spjs-chilipeppr.c9users.io/widget.html", // The standalone working widget so can view it working by itself
publish: {
'/list' : "Sends the list of serial ports shown in this widget including the connect state so other widgets/elements in ChiliPeppr can use the list including knowing what serial ports to send/recv from. Send in /getList and get back a /list with the JSON payload of the list.",
'/listAfterMetaDataAdded' : "Similar to /list but the list will have meta data added to it like an image, or default baud rates, or a modified friendly name. It may even be marked as deleted for dual port scenarios where a port may be considered the 2nd port.",
'/ws/onconnect' : 'When the websocket connects. This widget currently supports only a single websocket. In the future, multiple websockets will be supported and a ws identifier will be attached. For now, you will receive the string "connected" in the payload. The 2nd parameter will be the websocket in case you need it like to retrieve the IP address of SPJS. For multiple websockets an additional parameter will be published with the ws:// url',
'/ws/ondisconnect' : "When the websocket disconnects.",
'/ws/sys' : "A system message. Mostly for visual display like an error.",
'/ws/recv' : "A signal published when the websocket receives data from the serial port server. The serial port, i.e. COM21, the websocket identifier, and data are sent.",
'/onportopen' : 'Published when the Serial Port JSON Server tells us a port was opened. This could happen from the user clicking to open, or if another browser or websocket client opens it, we will fire off this signal as well. The payload looks like {Cmd: "Open", Desc: "Got register/open on port.", Port: "COM22", Baud: 115200, BufferType: "tinyg"} ',
'/onportclose' : 'Published when the Serial Port JSON Server tells us a port was closed. This could happen from the user clicking to close, or if another browser, or SPJS, or websocket client closes it, we will fire off this signal. The payload looks like {Cmd: "Close", Desc: "Got unregister/close on port.", Port: "COM22", Baud: 115200} ',
'/onportopenfail' : 'Published when the Serial Port JSON Server tells us a port was attempting to be opened but failed for some reason. This could happen from the user clicking to open, or if another browser tries to open, but an error arose such as the port being locked by another process. The payload looks like {Cmd: "OpenFail", Desc: "Got error reading on port. ", Port: "COM22", Baud: 115200}',
'/recvline' : "We publish this signal in tandem with /ws/recv but we only publish this signal per newline. That way your widget can consume per line data which is typically the way you want it. We recommend you subscribe to this channel instead of /ws/recv to have less work to do of looking for newlines. When in setSingleSelectMode() we will only send you data for the port that is selected (in green in UI). You will not get this signal for secondary ports that are open. For secondary ports, you need to subscribe to /ws/recv and do lower level parsing.",
'/recvVersion' : "We send you this back if you published a /requestVersion signal. This is so other widgets can pivot off of what version of Serial Port JSON Server is running. For example, the Arduino/Atmel programmer sends in a /requestVersion to get a callback on /recvVersion to determine if you are at version 1.83 or above to know whether you have the correct functionality.",
'/recvSingleSelectPort' : "In case any other widget/element wants to know what port is single selected (when in setSingleSelectMode()), they can send a signal to /requestSingleSelectPort and we'll respond back with this signal with an object like: " + JSON.stringify({
"Name": "COM22",
"Friendly": "USB Serial Port (COM22)",
"IsOpen": true,
"Baud": 115200,
"RtsOn": true,
"DtrOn": false,
"BufferAlgorithm": "tinyg",
"AvailableBufferAlgorithms": [
"default",
"tinyg",
"dummypause"
],
"Ver": 1.7
}, undefined, 2) + ". Will send back a null if no ports or no singleSelectPort is defined.",
'/onQueue' : 'This signal is published when a command is queued on SPJS. Payload is {"Id":"123", "D":"G0 X1\n", "QCnt":1, "Port":"COM2"}. You get the data back because if another browser sent into the SPJS, you get that data reflected in other browsers which is important for synchronizing. See /jsonSend for more info.',
'/onWrite' : 'This signal is published when a command is written to the serial port on SPJS. Payload is {"Id":"123", "QCnt":0, "Port":"COM2"}. The serial command is not reiterated in this signal like it is in /onQueue. See /jsonSend for more info.',
'/onComplete' : 'This signal is published when a command is done being written on SPJS and is known to have been processed by the serial device. Payload is {"Id":"123"}. Please note that sometimes /onComplete could come back before /onWrite due to the multi-threaded nature of serial ports and writing/reading as well as network congestion. See /jsonSend for more info.' ,
'/onError' : 'This signal is published when a command produces an error in the CNC controller either due to a gcode syntax problem, or an unsupported gcode command. This signal can be used by the cnc-interface widget to handle for errors, or pause/cancel gcode execution so that the problem can be rectified.',
'/onBroadcast' : 'This signal is published when we see a broadcast message come in from SPJS and we simply regurgitate it out on this signal for any widget to listen to. To send a broadcast signal into SPJS you just use the command \"broadcast blah blah\" and then SPJS re-broadcasts that to all listeners with a packet like {Cmd:\"Broadcast\", Msg:\"blah blah\"}. For example, the ShuttleXpress CNC jog shuttle connects to SPJS on its own and when you click buttons on the device it broadcasts them to SPJS so widgets inside ChiliPeppr can respond to those clicks.',
'/onAnnounce' : 'This signal is published when we see an announce message come in from SPJS and we simply regurgitate it out on this signal for any widget to listen to. An announce signal is part of the Cayenn protocol. Basically an IoT device like an ESP8266 sends in a UDP broadcast to the network announcing its existence. SPJS listens for those and then sends a copy of the announcement to any SPJS listeners, like us. Then this SPJS widget publishes it out so other widgets inside ChiliPeppr can listen for the message.',
'/onFeedRateOverride' : 'This signal is published when we get a feed rate override update from SPJS. It will contain the payload similar to {"Cmd":"FeedRateOverride","Desc":"Providing you status of feed rate override.","Port":"COM7","FeedRateOverride":0,"IsOn":false}',
'/recvStatus' : 'Send in a /requestStatus and we will send you back a /recvStatus letting you know if SPJS is connected or not to the Serial Port JSON Server. The payload that comes to you in /recvStatus looks like {"Connected":true, "Websocket": ws } or {"connected":false, "websocket":null}. If you want to be pushed an event when the socket connects or disconnects you should subscribe to /ws/onconnect and /ws/ondisconnect'
},
subscribe: {
'/ws/send' : `This widget subscribes to this signal so anybody can publish
to SPJS by publishing here. You can send any command that SPJS supports. Please see the
docs for all support SPJS commands on Github at
<a target="_blank" href="https://github.com/chilipeppr/serial-port-json-server#supported-commands">https://github.com/chilipeppr/serial-port-json-server#supported-commands</a>.
<br><br>
Example<br>
chilipeppr.publish("/com-chilipeppr-widget-serialport/ws/send", "send COM22 G0 X0\\n");
<br><br>
Example of sending non-buffered command<br>
chilipeppr.publish("/com-chilipeppr-widget-serialport/ws/send", "sendnobuf /dev/ttyUSB0 M3 S1000\\n");
`,
'/send' : `This widget subscribes to this signal whereby you can simply send
to this pubsub channel (instead of /ws/send which is lower level) and the widget will
send to the default serial ports that you are connected to (the green highlight in the UI).
Most serial devices expect newline characters, so you should send those in your string as
this pubsub channel does not add them.
<br><br>
Example<br>
chilipeppr.publish("/com-chilipeppr-widget-serialport/send", "G1 X10 F500\\n");
`,
'/jsonSend' : '<p>This signal is like /send but a more structured version where you can send us commands like {"D": "G0 X1\n", "Id":"123"} or an array like [{"D": "G0 X1\n", "Id":"123"}, {"D": "G0 X2\n", "Id":"124"}] and then this widget will send callback signals in order of /onQueue, /onWrite, /onComplete. The payload is {"Id":"123"} on each of those.</p> <p>The SPJS has 3 steps to get your command to the serial device. Step 1 is /onQueue and this will come back immediately when SPJS has taken your command and queued it to memory/disk. Step 2 is /onWrite when SPJS actually has written your command to the serial device. If the device takes a while to execute the command it could be a bit of time until that command is physically executed. Step 3 is /onComplete which is SPJS attempting to watch for a response from the serial device to determine that indeed your command is executed. Please note /onComplete can come back prior to /onWrite based on your serial device and how fast it may have executed your serial command.</p> <p>You can omit the Id if you do not care about tracking. You will get callbacks with an empty Id so you will not be able to match them up. If you send in /jsonSend {"D": "G0 X1\nG0 X0\n", "Id":"123"} you will get back /onQueue [{"D":"G0 X1\n","Id":"123","Buf":"Buf"},{"D":"G0 X0\n","Id":"123-part-2-2","Buf":"Buf"}] because technically those are 2 commands with one Id. Some commands sent into Serial Port JSON Server get additional commands auto-added. For example, if you send in a command to TinyG that would put it in text mode, SPJS appends a command to put TinyG back in JSON mode. In those cases you will get parts added to your command and will see that in the response.</p>',
'/getlist' : "In case any other widget/element wants to request the list at any time, they can send a signal to this channel and we'll respond back with a /list",
'/requestVersion' : "Send in this signal to get back a /recvVersion. This is so other widgets can pivot off of what version of Serial Port JSON Server is running. For example, the Arduino/Atmel programmer sends in a /requestVersion to get a callback on /recvVersion to determine if you are at version 1.83 or above to know whether you have the correct functionality.",
'/requestSingleSelectPort' : "In case any other widget/element wants to know what port is single selected (when in setSingleSelectMode()), they can send a signal to this channel and we'll respond back with a /recvSingleSelectPort with an object like: " + JSON.stringify({
"Name": "COM22",
"Friendly": "USB Serial Port (COM22)",
"IsOpen": true,
"Baud": 115200,
"RtsOn": true,
"DtrOn": false,
"BufferAlgorithm": "tinyg",
"AvailableBufferAlgorithms": [
"default",
"tinyg",
"dummypause"
],
"Ver": 1.7
}, undefined, 2) + ". Will send back a null if no ports or no singleSelectPort is defined.",
'/requestFro' : 'Send in this signal to have this widget send in a request to SPJS for the Feed Rate Override status on the singleSelectPort, i.e. the port that is hilited green. This widget will send SPJS something like "fro COM7" and then the data will come back and a publish will occur on /onFeedRateOverride. If you send in an empty payload this will simply request the status. If you send in a float or integer it will actually set the Feed Rate Override multiplier to that value.',
'/requestStatus' : 'If you want to request the connected/disconnected status of this widget, you can send this pubsub signal in and we will send you back the connected status in the /recvStatus signal. We will also include the websocket object in case you were interested in it. Please see docs for /recvStatus for further info.'
},
foreignPublish: {
'/com-chilipeppr-elem-flashmsg/flashmsg' : "We publish system messages from the serial port server to the flash message element to display informational messages to the user.",
'/com-chilipeppr-interface-cnccontroller/plannerpause' : 'We publish a planner pause if we see that the buffer count in the Serial Port JSON Server gets above 20,000.',
'/com-chilipeppr-interface-cnccontroller/plannerresume' : 'We publish a planner resume when we get back to 15,000.'
},
isWsConnected: false,
host: null,
portlist: null,
conn: null, // the websocket we're connected to (eventually make this an array so we can have multiple websockets)
isSingleSelectMode: false, // means you can multiple open ports, or only open one
singleSelectPort: null, // this will get set to the last port opened based on cookie or click
buffertype: null, // holds what buffertype to request on the "open comPort baud buffertype" command, if null we just don't send
defaultBaud: null, // holds default baud to put in the pulldown menu
defaultOptions: null, // holds the options passed in on an object
isInitted: false, // keep track in case user calls init() twice (like i've done)
init: function (host, buffertype, defaultBaud, buffertypeDescription) {
if (this.isInitted) {
console.warn("you just initted the serial port json server widget again? huh? returning");
return;
}
this.isInitted = true;
console.group("init of serial port widget");
// see if we were passed a buffertype
// this is an extra command now that the serial port json
// server supports buffer algorithms for specific types
// of hardware. by default no buffer flow control is needed
// like if you're controlling an arduino
// but in the case of tinyg and grbl it helps to have buffer
// flow be very close to the serial port itself
// so the serial port json server supports algorithms to be
// added via github and compiled in. you may request
// that algorithm here globally, or per serial port
// it's best to not do this globally since the goal of
// chilipeppr is to allow multiple serial port devices at
// the same time to control things like probes while sending
// gcode
// see if an options object was passed in instead of
// individual parameters
if (host && typeof host === "object") {
var opt = host;
this.defaultOptions = opt;
if ('isSingleSelectMode' in opt) this.setSingleSelectMode();
if ('defaultBuffer' in opt) buffertype = opt.defaultBuffer;
if ('defaultBaud' in opt) defaultBaud = opt.defaultBaud;
if ('bufferEncouragementMsg' in opt) buffertypeDescription = opt.bufferEncouragementMsg;
}
if (buffertype != null && buffertype.length > 0) {
this.buffertype = buffertype;
console.log("we have a buffertype being requested. buffertype:", this.buffertype);
// if they gave a description use that
var mydescription = '"' + buffertype + '"';
if (buffertypeDescription != null && buffertypeDescription.length > 0) {
mydescription = buffertypeDescription;
}
// also add extra msg to encourage the buffer choice
$('.com-chilipeppr-widget-serialport-bufferindicator').removeClass("hidden").find('.buffername').text(mydescription);
// set the buffer encouragement to be the full passed in
// description if the caller called us with the new defaultOptions
// value
if (this.defaultOptions && 'bufferEncouragementMsg' in this.defaultOptions) {
$('.com-chilipeppr-widget-serialport-bufferindicator').text(
this.defaultOptions.bufferEncouragementMsg
);
}
// Cheating a bit here, bu this seems to be the new std
// default baud rate out there
this.defaultBaud = 115200;
}
if (defaultBaud) {
console.log("setting defaultBaud:", defaultBaud);
this.defaultBaud = defaultBaud;
}
this.btnBarSetup();
this.consoleSetup();
this.statusWatcher();
this.wsConnect(null);
//this.wsConnect(null, host);
// allow dedupe mode
var that = this;
chilipeppr.subscribe("/" + this.id + "/dedupeOn", this, function (msg) {
console.log("spjs widget now in dedupe mode");
that.isInDeDupeMode = true;
});
chilipeppr.subscribe("/" + this.id + "/dedupeOff", this, function (msg) {
console.log("spjs widget no longer in dedupe mode");
that.isInDeDupeMode = false;
});
// setup onconnect pubsub event
chilipeppr.subscribe("/" + this.id + "/ws/onconnect", this, function (msg) {
this.getPortList();
});
// setup recv pubsub event
// this is when we receive data from the serial port
chilipeppr.subscribe("/" + this.id + "/ws/recv", this, function (msg) {
this.onWsMessage(msg);
});
// setup low-level send pubsub event
// this is when a widget sends data to the serial port
chilipeppr.subscribe("/" + this.id + "/ws/send", this, function (msg) {
this.wsSend(msg);
});
// setup send pubsub event
// this is when a widget sends data to the serial port
// this only supports singleSelectMode()
chilipeppr.subscribe("/" + this.id + "/send", this, function (msg) {
this.send(msg);
});
// setup jsonSend pubsub event
// this is when a widget sends data to the serial port
// in a structured way so they can get callbacks
// this only supports singleSelectMode()
chilipeppr.subscribe("/" + this.id + "/jsonSend", this, function (json) {
this.sendViaJson(json);
});
// Allow others to request our serial port list
chilipeppr.subscribe("/" + this.id + "/getlist", this, function () {
chilipeppr.publish("/" + this.id + "/list", this.portlist);
});
var that = this;
// show last remote host, if there is one
if ($.cookie('lasthost')) {
var lasthost = $.cookie('lasthost');
lasthost = lasthost.replace(/ws:\/\/(.*):.*/, "$1");
$('#com-chilipeppr-widget-serialport-host').val(lasthost);
}
// setup convenience localhost href click
$('.spjs-connect2localhost').click(function() {
$('#com-chilipeppr-widget-serialport-host').val("localhost");
that.onRemoteHostConnect();
});
$('.spjs-connect2localhostSSL').click(function() {
$('#com-chilipeppr-widget-serialport-host').val("wss://localhost:8990/ws");
that.onRemoteHostConnect();
});
// if connect btn or enter key on remote host connect
var remoteCon = $('#com-chilipeppr-widget-serialport-hostbtn');
remoteCon.click(function() {
that.onRemoteHostConnect();
});
$('#com-chilipeppr-widget-serialport-host').keypress(function(event){
//console.log("got keypress. event:", event);
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13'){
that.onRemoteHostConnect();
}
});
// setup the port scan button
$('#com-chilipeppr-widget-serialport-scanbtn').click(function() {
var subnet = $('#com-chilipeppr-widget-serialport-scan').val();
that.wsScan(null, subnet);
});
// cleanup popovers that are getting created by some other widget's code
//$('.com-chilipeppr-widget-serialport').find('.popover').remove();
// setup requestSingleSelectPort pubsub event
chilipeppr.subscribe("/" + this.id + "/requestSingleSelectPort", this, function (msg) {
this.publishSingleSelectPort();
});
// subscribe to our own /onportopen signal to hide the buffer encouragement msg
chilipeppr.subscribe("/" + this.id + "/onportopen", this.hideBufferEncouragement.bind(this));
chilipeppr.subscribe("/" + this.id + "/list", this.bufferEncouragement.bind(this));
this.initBody();
console.log("setting up onPlannerResumeSetup");
this.onPlannerResumeSetup();
// setup cloud servers
this.setupCloudServers();
// make it so the pubsub signals of /requestVersion and /recvVersion
// work
this.setupVersionPubSub();
// setup /requestFro
this.setupFroPubSub();
this.setupStatusPubSub();
this.setupRecentServerList();
this.showRecentServerList();
this.setupSubnetScan();
console.log(this.name + " done loading.");
console.groupEnd();
},
setupSubnetScan: function() {
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};
pc.createDataChannel(""); //create a bogus data channel
pc.createOffer(pc.setLocalDescription.bind(pc), noop); // create offer and set local description
pc.onicecandidate = function(ice){ //listen for candidate events
if(!ice || !ice.candidate || !ice.candidate.candidate) return;
var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];
console.log('my IP: ', myIP);
var subnet = myIP.replace(/\d+$/, "*");
console.log("my IP subnet:", subnet);
$('#com-chilipeppr-widget-serialport-scan').val(subnet);
pc.onicecandidate = noop;
};
},
setupRecentServerList: function() {
var that = this;
$('.com-chilipeppr-widget-serialport-install .btn-reset-recent-server-list').click(function() {
localStorage.setItem('com-chilipeppr-widget-serialport-serverList', null);
that.showRecentServerList();
})
},
showRecentServerList: function() {
//debugger;
var serverList = this.serverListGet();
var elOuter = $('.com-chilipeppr-widget-serialport-install .recent-server-list-wrapper');
var el = $('.com-chilipeppr-widget-serialport-install .recent-server-list');
var that = this;
console.log("showRecentServerList:", serverList)
if (serverList && Object.keys(serverList).length > 0) {
// show it
el.empty();
for (var key in serverList) {
var val = serverList[key];
var elWs = $(val);
elWs.click(key, function(evt) {
console.log("got click. evt:", evt, "data:", evt.data);
that.disconnect();
that.wsConnect(evt.data);
});
el.append(elWs);
el.append("<br>");
}
elOuter.removeClass("hidden");
} else {
// hide it
el.html("(none)");
elOuter.addClass("hidden");
}
},
setupStatusPubSub: function() {
chilipeppr.subscribe("/" + this.id + "/requestStatus", this, this.onRequestStatus);
},
onRequestStatus: function() {
chilipeppr.publish('/' + this.id + '/recvStatus', {
connected: this.isWsConnected,
websocket: this.conn
});
},
setupFroPubSub: function() {
chilipeppr.subscribe("/" + this.id + "/requestFro", this, this.onRequestFro);
},
onRequestFro: function(payload) {
var multiplier = "";
if (payload) {
multiplier = payload;
}
chilipeppr.publish('/com-chilipeppr-widget-serialport/ws/send', 'fro ' + this.singleSelectPort + " " + multiplier + "\n");
},
version: null,
versionFloat: 0.0,
setupVersionPubSub: function() {
chilipeppr.subscribe("/" + this.id + "/requestVersion", this, this.onRequestVersion);
},
onRequestVersion: function() {
chilipeppr.publish("/" + this.id + "/recvVersion", this.versionFloat);
},
onVersion: function(version) {
console.log("got version cmd. version:", version);
this.version = version;
this.versionFloat = parseFloat(version);
$('.com-chilipeppr-widget-serialport .serial-port-version').text(" v" + version + " ");
// Handle functionality buttons show/hidden based on version here
if ( this.versionFloat >= 1.76) {
// show restart button
$('.com-chilipeppr-widget-serialport .btn.spjs-restart').parent().removeClass("hidden");
} else {
// hide restart button
$('.com-chilipeppr-widget-serialport .btn.spjs-restart').parent().addClass("hidden");
}
// Handle informational message here
if ( this.versionFloat >= 1.80) {
$('.com-chilipeppr-widget-serialport-version-yours').text(version);
$('.com-chilipeppr-widget-serialport-version').addClass('hidden');
} else if (version == "1.6" || version == "1.2" || version == "1.3" || version == "1.3.1" || version == "1.4" || version == "1.5" || version == "snapshot") {
$('.com-chilipeppr-widget-serialport-version-yours').text(version);
//$('.com-chilipeppr-widget-serialport-version').addClass('hidden');
$('.com-chilipeppr-widget-serialport-version-fullmsg').html(
"You are running version " + version + " of the Serial Port JSON Server. You MUST upgrade to the new 1.7 version as the Serial Port JSON Server has moved to a more stuctured send to enable onQueue, onWrite, and OnComplete events.<br/><br/>To upgrade, " +
'<button type="button" class="btn btn-xs btn-default disconnect-inline" data-toggle="popover" data-placement="auto" data-container="body" data-content="Disconnect from serial port server" data-trigger="hover" data-original-title="" title=""><span class="glyphicon glyphicon-remove-sign"></span></button>' +
" disconnect from the websocket server and click the correct platform to download the binary for.");
$('.com-chilipeppr-widget-serialport-version-fullmsg .disconnect-inline').click(this.disconnect.bind(this));
/*
} else if (version == "1.2") {
$('.com-chilipeppr-widget-serialport-version-fullmsg').html("You are running version 1.2 of the Serial Port JSON Server. If you are running a TinyG, you should upgrade to the new 1.6 version as the Serial Port JSON Server now supports buffer flow control plugins. A plugin has been written for TinyG that puts the control closer to the serial port to ensure no lost Gcode. If you are running an alternate workspace, you're all set, although you could still upgrade.<br/><br/>To upgrade, disconnect from the websocket server and click the correct platform to download the binary for.");
*/
} else {
if (version != null && version != "")
$('.com-chilipeppr-widget-serialport-version-yours').text(version);
$('.com-chilipeppr-widget-serialport-version').removeClass('hidden');
}
},
resetVersion: function() {
// turn off the version msg in UI
// to handle earlier versions that don't send a version num
// default to always showing. then onVersion will hide for us
$('.com-chilipeppr-widget-serialport-version-yours').text("1.1");
// no longer doing this as of Jan 25 2015 cuz version 1.1 is SOOOOO old nobody
// has it anymore
//$('.com-chilipeppr-widget-serialport-version').removeClass('hidden');
},
hideVersion: function() {
$('.com-chilipeppr-widget-serialport-version').addClass('hidden');
$('.com-chilipeppr-widget-serialport .panel-heading .serial-port-version').text('');
},
resetSpjsName: function() {
$('.com-chilipeppr-widget-serialport .panel-heading .hosttitle').text('');
},
onSpjsName: function(spjsName) {
$('.com-chilipeppr-widget-serialport .panel-heading .hosttitle').text(spjsName);
},
setupCloudServers: function() {
// make everything clickable
$('.com-chilipeppr-widget-serialport-body .cloud-card').click(this.onCloudServerClick.bind(this));
},
onCloudServerClick: function(evt) {
console.log("got onCloudServerClick. evt:", evt, "data:", evt.data);
var wsUrl = $(evt.currentTarget).data("ws");
console.log("url from data attrib:", wsUrl);
this.disconnect();
this.wsConnect(wsUrl);
},
showBufferEncouragement: function() {
$('.com-chilipeppr-widget-serialport-bufferindicator').removeClass('hidden');
},
hideBufferEncouragement: function() {
$('.com-chilipeppr-widget-serialport-bufferindicator').addClass('hidden');
},
bufferEncouragement: function(list, arg2) {
console.log("got bufferEncouragement port list:", list, "arg2:", arg2);
//$('.com-chilipeppr-widget-serialport-bufferindicator').addClass('hidden');
// see if we're being asked to show a default buffer. if we are then we need
// to analayze the current port list to see if anything is open with that buffer
// set. if it is we can hide the encouragement msg. if it's not, we should show the msg
//debugger;
var that = this;
if (this.buffertype != null && list != null && list.length > 0) {
// yes, the instantiator wants a certain type of buffer to be used
var isAnythingConnectedWithTheBufferWeWant = false;
// process whole port list
list.forEach(function(item) {
//debugger;
if (item.IsOpen && item.BufferAlgorithm.startsWith(that.buffertype)) {
isAnythingConnectedWithTheBufferWeWant = true;
}
});
if (isAnythingConnectedWithTheBufferWeWant)
this.hideBufferEncouragement();
else
this.showBufferEncouragement();
}
},
publishSingleSelectPort: function() {
console.log("got publishSingleSelectPort. isSingleSelectMode:", this.isSingleSelectMode, "singleSelectPort:", this.singleSelectPort, "portlist:", this.portlist);
var port = null;
var that = this;
if (this.portlist && this.portlist != null) {
this.portlist.forEach(function(item) {
console.log("item:", item);
if (item.Name == that.singleSelectPort) {
console.log("found it. item.Name:", item.Name);
port = item;
}
});
}
chilipeppr.publish("/com-chilipeppr-widget-serialport/recvSingleSelectPort", port);
},
onRemoteHostConnect: function() {
console.log("onRemoteHostConnect");
var host = $('#com-chilipeppr-widget-serialport-host').val();
$('#com-chilipeppr-widget-serialport-hostconnectmsg').html(
"Trying to connect to " +
$('#com-chilipeppr-widget-serialport-host').val() + "...");
this.wsConnect(host, function() {
$('#com-chilipeppr-widget-serialport-hostconnectmsg').html("Last connect successful.");
}, function() {
$('#com-chilipeppr-widget-serialport-hostconnectmsg').html("Failed to connect to host.");
});
},
setSingleSelectMode: function() {
this.isSingleSelectMode = true;
//var ver = " v" + this.version;
//if (this.version == null) ver = "";
$('.com-chilipeppr-widget-serialport .panel-heading .subtitle').html('Single Port Mode');
this.singleSelectPort = $.cookie("singleSelectPort");
console.log("setSingleSelectMode. port:", this.singleSelectPort);
},
getPortListCount: 0,
getPortList: function () {
if (this.isWsConnected) {
this.getPortListCount = 0;
this.wsSend("list");
} else {
if (this.getPortListCount > 5) {
// give up, so we don't get in endless loop
this.publishSysMsg("Tried to get serial port list, but we are not connected to serial port json server.");
} else {
this.getPortListCount++;
this.wsConnect();
}
}
},
btnBarSetup: function () {
var that = this;
/*
$('.com-chilipeppr-widget-serialport .btn').tooltip({
animation: true,
delay: 100,
//container: 'body'
});
*/
$('.com-chilipeppr-widget-serialport .btn').popover({
animation: true,
delay: 100,
//container: 'body'
});
$('.com-chilipeppr-widget-serialport .btn.refresh').click(function () {
$('.com-chilipeppr-widget-serialport-disconnected .refresh').prop('disabled', true);
that.getPortList();
});
$('#com-chilipeppr-widget-serialport-tbar-showhideconsole').click(
this.consoleToggle.bind(this)
);
$('#com-chilipeppr-widget-serialport-tbar-showhidestatus').click(
this.statusToggle.bind(this)
);
$('#com-chilipeppr-widget-serialport-tbar-refresh').click(function () {
that.getPortList();
});
$('#com-chilipeppr-widget-serialport-tbar-reconws').click(function () {
that.wsConnect();
});
$('#com-chilipeppr-widget-serialport-tbar-disconws').click(this.disconnect.bind(this));
$('.com-chilipeppr-widget-serialport .btn.disconnect').click(this.disconnect.bind(this));
// the new restart command
$('.com-chilipeppr-widget-serialport .btn.spjs-restart').click(function () {
that.restartSpjs();
});
this.forkSetup();
},
restartSpjs: function() {
this.wsSend("restart");
},
exitSpjs: function() {
this.wsSend("exit");
},
disconnect: function() {
//console.log("got forced disconnect, so wiping cookie storing lasthost");
//$.removeCookie('lasthost', { path: '/' }); // => true
console.log("closing websocket:", this.conn);
if (this.conn) {
this.conn.close();
$('.com-chilipeppr-widget-serialport-install').removeClass('hidden');
}
},
consoleToggle: function() {
var con = $('.com-chilipeppr-widget-serialport-console');
var coni = $('.com-chilipeppr-widget-serialport-consoleinput');
if (con.hasClass('hidden')) {
// the console is hidden, so let's show
con.removeClass('hidden');
coni.removeClass('hidden');
this.logIsShowing = true;
} else {
// it's showing, so they want to hide it
con.addClass('hidden');
coni.addClass('hidden');
this.logIsShowing = false;
}
},
statusToggle: function() {
var stat = $('.com-chilipeppr-widget-serialport-status');
if (stat.hasClass('hidden')) {
// the status is hidden, so let's show
stat.removeClass('hidden');
} else {
// it's showing, so they want to hide it
stat.addClass('hidden');
}
},
history: [], // store history of commands so user can iterate back
historyLastShownIndex: null, // store last shown index so iterate from call to call
pushOntoHistory: function(cmd) {
this.history.push(cmd);
// push onto dropup menu
//var el = $('<li><a href="javascript:">' + cmd + '</a></li>');
//$('#com-chilipeppr-widget-spconsole-consoleform .dropdown-menu').append(el);
//el.click(cmd, this.onHistoryMenuClick.bind(this));
},
onHistoryMenuClick: function(evt) {
console.log("got onHistoryMenuClick. data:", evt.data);
$("#com-chilipeppr-widget-spconsole-consoleform input").val(evt.data);
//return true;
},
consoleSetup: function () {
// subscribe to websocket events
chilipeppr.subscribe("/" + this.id + "/ws/recv", this, function (msg) {
var msg = $("<div/>").text(msg);
this.appendLog(msg);
});
var that = this;
$("#com-chilipeppr-widget-serialport-consoleform").submit(function (evt) {
evt.preventDefault();
console.log("got submit on form");
if (!that.isWsConnected) {