-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathauto-generated-widget.html
1642 lines (1433 loc) · 75.2 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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Widget / Cam</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'>
/* CSS for ChiliPeppr Widget */
#com-chilipeppr-widget-cam {
margin:10px;
}
#com-chilipeppr-widget-cam .nav-tabs>li>a {
padding: 2px 6px;
}
#com-chilipeppr-widget-cam .panel-body {
padding:0;
/*min-height:200px;*/
}
#com-chilipeppr-widget-cam .overlayWrapper {
position:relative;
margin:0;
padding:0;
}
#com-chilipeppr-widget-cam .cam-line-horiz {
border-top: 1px solid red;
top:50%;
left:0;
right:0;
position:absolute;
}
#com-chilipeppr-widget-cam .cam-line-vert {
border-left: 1px solid red;
top:0;
left:50%;
bottom:0;
position:absolute;
}
#com-chilipeppr-widget-cam .well {
margin-bottom:0;
}
#com-chilipeppr-widget-cam .terminal {
background-color:#000000;
margin-top:14px;
color:#cccccc;
overflow:auto;
max-height:150px;
}
#com-chilipeppr-widget-cam .videoWrapper {
background-color: black;
position:relative;
margin:0;
padding:0;
}
.cam-img {
height:41px;
width:50px;
float:left;
margin-right:10px;
background-size: cover;
border-radius: 4px;
background-image:url('cam-generic3.png');
}
</style>
<script type='text/javascript'>
//<![CDATA[
/*global requirejs cprequire cpdefine chilipeppr THREE*/
// ignore this errormessage:
// 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.
}
});
cprequire_test(["inline:com-chilipeppr-widget-cam"], function(myWidget) {
// Test this element. This code is auto-removed by the chilipeppr.load()
// when using this widget in production. So use the cpquire_test to do things
// you only want to have happen during testing, like loading other widgets or
// doing unit tests. Don't remove end_test at the end or auto-remove will fail.
console.log("test running of " + myWidget.id);
$('body').prepend('<div id="testDivForFlashMessageWidget"></div>');
chilipeppr.load(
"#testDivForFlashMessageWidget",
"http://fiddle.jshell.net/chilipeppr/90698kax/show/light/",
function() {
console.log("mycallback got called after loading flash msg module");
cprequire(["inline:com-chilipeppr-elem-flashmsg"], function(fm) {
//console.log("inside require of " + fm.id);
fm.init();
});
}
);
//deactivate cuz of mixed ssl and non ssl content
// load spjs widget so we can test
//http://fiddle.jshell.net/chilipeppr/vetj5fvx/show/light/
$('body').append('<div id="testDivForSpjsWidget"></div>');
chilipeppr.load(
"#testDivForSpjsWidget",
//"http://fiddle.jshell.net/chilipeppr/vetj5fvx/show/light/",
"http://raw.githubusercontent.com/chilipeppr/widget-spjs/master/auto-generated-widget.html",
function() {
console.log("mycallback got called after loading spjs module");
cprequire(["inline:com-chilipeppr-widget-serialport"], function(spjs) {
//console.log("inside require of " + fm.id);
spjs.init();
spjs.consoleToggle();
// init my widget
myWidget.init();
$('#' + myWidget.id).css('margin', '10px');
$('#testDivForSpjsWidget').css('margin', '10px');
});
}
);
$('title').html(myWidget.name);
// myWidget.init();
} /*end_test*/ );
// This is the main definition of your widget. Give it a unique name.
cpdefine("inline:com-chilipeppr-widget-cam", ["chilipeppr_ready", /* other dependencies here */ ], function() {
return {
/**
* The ID of the widget. You must define this and make it unique.
*/
id: "com-chilipeppr-widget-cam", // Make the id the same as the cpdefine id
name: "Widget / Cam", // The descriptive name of your widget.
desc: "This widget loads a webcam view in ChiliPeppr via WebRTC.", // A description of what your widget does
url: "http://raw.githubusercontent.com/chilipeppr/widget-cam/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-cam", // 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-cam", // The backing github repo
testurl: "http://widget-cam-chilipeppr.c9users.io/widget.html", // The standalone working widget so can view it working by itself
/**
* Define pubsub signals below. These are basically ChiliPeppr's event system.
* ChiliPeppr uses amplify.js's pubsub system so please refer to docs at
* http://amplifyjs.com/api/pubsub/
*/
/**
* Define the publish signals that this widget/element owns or defines so that
* other widgets know how to subscribe to them and what they do.
*/
publish: {
// Define a key:value pair here as strings to document what signals you publish.
// '/onExampleGenerate': 'Example: Publish this signal when we go to generate gcode.'
},
/**
* Define the subscribe signals that this widget/element owns or defines so that
* other widgets know how to subscribe to them and what they do.
*/
subscribe: {
// Define a key:value pair here as strings to document what signals you subscribe to
// so other widgets can publish to this widget to have it do something.
// '/onExampleConsume': 'Example: This widget subscribe to this signal so other widgets can send to us and we'll do something with it.'
},
/**
* Document the foreign publish signals, i.e. signals owned by other widgets
* or elements, that this widget/element publishes to.
*/
foreignPublish: {
// Define a key:value pair here as strings to document what signals you publish to
// that are owned by foreign/other widgets.
// '/jsonSend': 'Example: We send Gcode to the serial port widget to do stuff with the CNC controller.'
},
/**
* Document the foreign subscribe signals, i.e. signals owned by other widgets
* or elements, that this widget/element subscribes to.
*/
foreignSubscribe: {
// Define a key:value pair here as strings to document what signals you subscribe to
// that are owned by foreign/other widgets.
// '/com-chilipeppr-elem-dragdrop/ondropped': 'Example: We subscribe to this signal at a higher priority to intercept the signal. We do not let it propagate by returning false.'
},
/**
* All widgets should have an init method. It should be run by the
* instantiating code like a workspace or a different widget.
*/
init: function() {
console.log("I am being initted. Thanks.");
this.setupUiFromLocalStorage();
this.btnSetup();
this.forkSetup();
//this.initCam();
setTimeout(this.initCheckForCam.bind(this), 2000);
this.setupPubSubForSpjsConnect();
//this.subscribeToLowLevelSerial();
// setup the install div buttons
this.uv4lSetupInstall();
// this.getMyLocalIp();
this.scanForSpjsServers();
console.log("I am done being initted.");
},
/**
* When this widget is activated
*/
activate: function() {
this.initCheckForCam();
},
/**
* When this widget is deactivated
*/
deactivate: function() {
},
// Scan for SPJS servers and cameras since the use case
// we are after is multiple Raspberry Pi's serving multiple
// cameras.
/**
* Scan for SPJS's much like the SPJS widget does it.
*/
scanForSpjsServers: function() {
// figure out my ip and thus my subnet
this.getMyLocalIp(function(data) {
console.log("got my ip. data:", data);
})
},
// ---------------
// Cam check/install region
// ---------------
/** When this widget is activated, we need to do a few things:
* 1. Check if there is a stored setting of what cam to connect to
* because this could be a different host than what SPJS is running
* on.
* If no setting:
* 1. Check if we are SPJS connected
* 2. Check if we are on a Raspberry Pi
* 3. If so, then see if uv4l is installed
* 4. If so, then launch it
* 5. Connect
* If not Raspi, show error.
* If no uv4l, go into install process.
*/
isRunningInitCheckForCam: false,
initCheckForCam: function() {
// check settings and see if there is a stored ip addr to connect to
console.log("initCheckForCam. initting check for cam");
if (this.isRunningInitCheckForCam) {
console.warn("we are currently running initCheckForCam. Exiting.");
return;
}
this.isRunningInitCheckForCam = true;
// lets ensure all our install msg divs are hidden
$('#' + this.id + " .install-msg").addClass("hidden");
//debugger;
var that = this;
// let's take an approach where we first try to connect to the webrtc server
this.webRtcGo(function(obj) {
console.log("webRtcGo result. obj:", obj);
if (obj.isSuccess) {
// cool, it worked
$('#' + that.id + " .isrunning").removeClass("hidden");
} else {
// we were not able to get webrtc as our 1st step
// else just try to see if spjs host is raspi, and has cam
this.checkIfSpjsConnected(function(results) {
if (results.connected) {
// great, we're connected, lets' do next step
$('#' + that.id + " .notconnected").addClass("hidden");
// check if we are on linux
that.checkIfLinux(function(status) {
console.log("initCheckForCam. got callback from checking if linux. status:", status);
if (status.OS.match(/linux/i)) {
if (status.Arch.match(/arm/i)) {
// check if allowexec
that.checkIfAllowExec(function(status) {
if (status.isAllowExec) {
that.checkIfRaspberryPi(function(status) {
// when we get here, we get back a status to determine
// if we're on a raspi or not
console.log("initCheckForCam. we got back from checkIfRaspberryPi. status:", status);
if (status.isRaspberryPi) {
// awesome. we are raspi.
// we can install
that.isRunningInitCheckForCam = false;
that.uv4lCheckIfInstalled(function(data) {
console.log("initCheckForCam. got check complete for uv4l. data:", data);
if (data.isInstalled) {
// let's see if it is running
that.checkIfUv4lIsRunning(function(results) {
if (results.isRunning) {
that.webRtcGo(function(payload) {
if (payload.result == "success") {
// cool, good to go
$('#' + that.id + " .isrunning").removeClass("hidden");
} else {
// got error
$('#' + that.id + " .isinstalled").removeClass("hidden");
}
});
} else {
// it is not running, let's launch it for them
$('#' + that.id + " .isinstalled").removeClass("hidden");
}
})
} else {
// not installed but eligible
$('#' + that.id + " .eligible").removeClass("hidden");
that.isRunningInitCheckForCam = false;
}
});
} else {
console.log("initCheckForCam. at least is linux. show error");
$('#' + that.id + " .linux").removeClass("hidden");
that.isRunningInitCheckForCam = false;
}
});
} else {
// not allowed, ask to restart spjs
// with cmd line switch
$('#' + that.id + " .allowexec").removeClass("hidden");
that.isRunningInitCheckForCam = false;
}
});
} else {
console.log("initCheckForCam. at least is linux. show error");
$('#' + that.id + " .linux").removeClass("hidden");
that.isRunningInitCheckForCam = false;
}
} else {
console.log("initCheckForCam. We are not Linux, so giving up. Show error");
var os = status.OS.charAt(0).toUpperCase() + status.OS.slice(1);
$('#' + that.id + " .bados .os").text(os);
$('#' + that.id + " .bados").removeClass("hidden");
that.isRunningInitCheckForCam = false;
}
});
} else {
// not connected, show error
$('#' + that.id + " .notconnected").removeClass("hidden");
that.isRunningInitCheckForCam = false;
}
});
}
});
},
// WEBRTC CONNECTION METHODS
webRtcCallback: null,
/**
* Use this as your main entry point. You need to provide a callback which
* will be told success or error.
*/
webRtcGo: function(callback) {
this.webRtcCallback = callback;
this.webRtcInit();
this.webRtcStart();
// bind button click events
$('#com-chilipeppr-widget-cam .btn-startstreaming').click(this.onBtnStartClick.bind(this));
$('#com-chilipeppr-widget-cam .btn-stopstreaming').click(this.onBtnStopClick.bind(this));
},
onBtnStartClick: function(evt) {
// hide popover
$('#' + this.id + " .btn-startstreaming").popover('hide');
this.webRtcStart();
},
onBtnStopClick: function(evt) {
// hide popover
$('#' + this.id + " .btn-stopstreaming").popover('hide');
this.webRtcStop();
},
/**
* Called after successfully streaming remote video
*/
onWebRtcSuccess: function(stream) {
this.webRtcCallback({isSuccess: true, result:"success", stream: stream});
// get the video tag and print debug
var vidEl = $('#com-chilipeppr-widget-cam-remote-video');
console.log("vidEl:", vidEl);
console.log("video:", vidEl[0]);
},
/**
* Called if failure connecting and streaming.
*/
onWebRtcError: function(errMsg) {
this.webRtcCallback({isSuccess: false, result:"error", msg:errMsg});
},
/**
* Trigger the initial check of whether WebRTC is running on the server.
*/
webRtcInit: function() {
// chech that we have an spjs ip addr
if (this.ipAddrForSpjs && this.ipAddrForSpjs.length > 0)
this.webRtcSignallingServerAddress = this.ipAddrForSpjs + ':8080';
else {
this.onWebRtcError("No IP address for SPJS.");
return;
}
this.webRtcWs = null;
this.webRtcPc;
// this.webRtcAudioVideoStream;
this.webRtcRemoteStream = null;
this.pcConfig = {"iceServers": [
{"urls": ["stun:stun.l.google.com:19302", "stun:" + this.ipAddrForSpjs + ":3478"]}
]};
this.pcOptions = {
optional: [
{DtlsSrtpKeyAgreement: true}
]
};
this.mediaConstraints = {
optional: [],
mandatory: {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
}
};
this.URL = window.URL || window.webkitURL;
this.RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
this.RTCSessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
this.RTCIceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;
navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
// actually start the connection
// this.webRtcStart();
},
webRtcCeatePeerConnection: function() {
try {
var pcConfig = this.pcConfig;
console.log(JSON.stringify(pcConfig));
this.webRtcPc = new this.RTCPeerConnection(pcConfig, this.pcOptions);
this.webRtcPc.onicecandidate = this.onWebRtcIceCandidate.bind(this);
this.webRtcPc.onaddstream = this.onWebRtcRemoteStreamAdded.bind(this);
this.webRtcPc.onremovestream = this.onWebRtcRemoteStreamRemoved.bind(this);
console.log("peer connection successfully created!");
} catch (e) {
console.log("createPeerConnection() failed");
this.onWebRtcError("createPeerConnection() failed");
return false;
}
return true;
},
onWebRtcIceCandidate: function(event) {
if (event.candidate) {
var candidate = {
sdpMLineIndex: event.candidate.sdpMLineIndex,
sdpMid: event.candidate.sdpMid,
candidate: event.candidate.candidate
};
var command = {
command_id: "addicecandidate",
data: JSON.stringify(candidate)
};
this.webRtcWs.send(JSON.stringify(command));
} else {
console.log("End of candidates.");
}
},
onWebRtcRemoteStreamAdded: function(event) {
console.log("onWebRtcRemoteStreamAdded. event:", event);
console.log("Remote stream added:", this.URL.createObjectURL(event.stream));
var remoteVideoElement = document.getElementById('com-chilipeppr-widget-cam-remote-video');
remoteVideoElement.src = this.URL.createObjectURL(event.stream);
remoteVideoElement.play();
event.stream.onaddtrack = this.onWebRtcOnAddTrack.bind(this);
event.stream.onactive = this.onWebRtcOnActive.bind(this);
this.webRtcRemoteStream = event.stream;
// call success function
this.onWebRtcSuccess(event.stream);
this.webRtcPrintVideoInfo();
},
onWebRtcOnAddTrack: function(event) {
console.log("onWebRtcTrackAdded. event:", event);
},
onWebRtcOnActive: function(event) {
console.log("onWebRtcOnActive. event:", event);
},
onWebRtcRemoteStreamRemoved: function(event) {
var remoteVideoElement = document.getElementById('com-chilipeppr-widget-cam-remote-video');
remoteVideoElement.src = '';
},
webRtcOffer: function(stream) {
this.webRtcCeatePeerConnection();
if (stream) {
this.webRtcPc.addStream(stream);
}
var command = {
command_id: "offer",
options: {
force_hw_vcodec: $('#' + this.id + ' .remote_hw_vcodec').is(':checked'), //document.getElementById("remote_hw_vcodec").checked,
vformat: $('#' + this.id + ' .remote_vformat').val() //document.getElementById("remote_vformat").value
}
};
this.webRtcWs.send(JSON.stringify(command));
console.log("offer(), command=" + JSON.stringify(command));
},
webRtcStart: function() {
var that = this;
if ("WebSocket" in window) {
$('#com-chilipeppr-widget-cam .btn-stopstreaming').prop('disabled', false);
$('#com-chilipeppr-widget-cam .btn-startstreaming').prop('disabled', true);
// document.getElementById("stop").disabled = false;
// document.getElementById("start").disabled = true;
// document.documentElement.style.cursor ='wait';
//server = document.getElementById("signalling_server").value.toLowerCase();
var server = this.webRtcSignallingServerAddress;
var protocol = "ws:"; //location.protocol === "https:" ? "wss:" : "ws:";
this.webRtcWs = new WebSocket(protocol + '//' + server + '/stream/webrtc');
this.webRtcWs.onopen = function () {
console.log("onopen()");
// that.audio_video_stream = null;
that.webRtcOffer();
};
this.webRtcWs.onmessage = function (evt) {
var msg = JSON.parse(evt.data);
//console.log("message=" + msg);
console.log("type=" + msg.type);
switch (msg.type) {
case "offer":
that.webRtcPc.setRemoteDescription(new that.RTCSessionDescription(msg),
function onRemoteSdpSuccess() {
console.log('onRemoteSdpSucces()');
that.webRtcPc.createAnswer(function(sessionDescription) {
that.webRtcPc.setLocalDescription(sessionDescription);
var command = {
command_id: "answer",
data: JSON.stringify(sessionDescription)
};
that.webRtcWs.send(JSON.stringify(command));
console.log(command);
}, function (error) {
alert("Failed to createAnswer: " + error);
}, that.mediaConstraints);
},
function onRemoteSdpError(event) {
alert('Failed to set remote description (unsupported codec on this browser?): ' + event);
that.webRtcStop();
}
);
var command = {
command_id: "geticecandidate"
};
console.log(command);
that.webRtcWs.send(JSON.stringify(command));
break;
case "answer":
break;
case "message":
alert(msg.data);
break;
case "geticecandidate":
var candidates = JSON.parse(msg.data);
for (var i = 0; candidates && i < candidates.length; i++) {
var elt = candidates[i];
var candidate = new that.RTCIceCandidate({sdpMLineIndex: elt.sdpMLineIndex, candidate: elt.candidate});
that.webRtcPc.addIceCandidate(candidate,
function () {
console.log("IceCandidate added: " + JSON.stringify(candidate));
},
function (error) {
console.log("addIceCandidate error: " + error);
}
);
}
// document.documentElement.style.cursor ='default';
// that.webRtcPrintVideoInfo();
break;
}
};
that.webRtcWs.onclose = function (evt) {
if (that.webRtcPc) {
that.webRtcPc.close();
that.webRtcPc = null;
}
$('#com-chilipeppr-widget-cam .btn-stopstreaming').prop('disabled', true);
$('#com-chilipeppr-widget-cam .btn-startstreaming').prop('disabled', false);
// document.getElementById("stop").disabled = true;
// document.getElementById("start").disabled = false;
// document.documentElement.style.cursor ='default';
};
that.webRtcWs.onerror = function (evt) {
//alert("An error has occurred!");
if (that.webRtcWs) that.webRtcWs.close();
that.onWebRtcError("Error with websocket. Likely that UV4l server is not running.");
};
} else {
alert("Sorry, this browser does not support WebSockets.");
this.onWebRtcError("No websocket support. How old is your browser?");
}
},
webRtcPrintVideoInfo: function() {
if (this.webRtcRemoteStream) {
console.log("track info:");
for (var i = 0; i < this.webRtcRemoteStream.getTracks().length; i++) {
var track = this.webRtcRemoteStream.getTracks()[i];
console.log(track);
// console.log("track settings:", track.getSettings());
// console.log("track capability:", track.getCapabilities());
// console.log("track constraints:", track.constraints());
}
}
},
webRtcStop: function() {
/* Don't need this section cuz for local video
if (this.audio_video_stream) {
try {
this.audio_video_stream.stop();
} catch (e) {
for (var i = 0; i < this.audio_video_stream.getTracks().length; i++)
this.audio_video_stream.getTracks()[i].stop();
}
this.audio_video_stream = null;
} */
// CONTINUE HERE...
document.getElementById('com-chilipeppr-widget-cam-remote-video').src = '';
// document.getElementById('local-video').src = '';
if (this.webRtcPc) {
this.webRtcPc.close();
this.webRtcPc = null;
}
if (this.webRtcWs) {
this.webRtcWs.close();
this.webRtcWs = null;
}
// document.getElementById("stop").disabled = true;
// document.getElementById("start").disabled = false;
// document.documentElement.style.cursor ='default';
$('#' + this.id + " .btn-stopstreaming").prop('disabled', true);
$('#' + this.id + " .btn-startstreaming").prop('disabled', false);
console.log("stopped webrtc");
},
// END WEBRTC CONNECTION METHODS
/**
* Subscribe to connect/disconnect events for SPJS so we can pivot off
* of it for detection.
*/
setupPubSubForSpjsConnect: function() {
chilipeppr.subscribe('/com-chilipeppr-widget-serialport/ws/onconnect', this, this.onSpjsConnect);
chilipeppr.subscribe('/com-chilipeppr-widget-serialport/ws/ondisconnect', this, this.onSpjsDisconnect);
},
ipAddrForSpjs: null,
onSpjsConnect: function(payload, more) {
console.log("onSpjsConnect. payload:", payload, "more:", more);
// "ws://192.168.1.34:8989/ws"
var websocket = more.websocket;
if (websocket && websocket.url && websocket.url.match(/wss{0,1}:\/\/(.*):/)) {
this.ipAddrForSpjs = RegExp.$1;
console.log("onSpjsConnect. got ip of websocket conn. ip:", this.ipAddrForSpjs);
}
// check for cam 1 sec later
setTimeout(this.initCheckForCam.bind(this), 1000);
},
onSpjsDisconnect: function() {
this.initCheckForCam();
},
/**
* Send the execruntime command to the currently running SPJS to see what
* OS is running.
*/
sendExecRuntime: function() {
chilipeppr.publish("/com-chilipeppr-widget-serialport/ws/send", "execruntime");
},
/**
* Send a terminal command to the currently running SPJS.
*/
send: function(cmd) {
chilipeppr.publish("/com-chilipeppr-widget-serialport/ws/send", "exec " + cmd);
},
isInSendSyncMode: false,
sendSyncCallback: null,
sendSyncIdNum: 0,
/**
* Send synchronously with callback as if you were right at the command line
*/
sendSync: function(cmd, callback) {
if (this.isInSendSyncMode) {
console.error("Cannot sendSync twice while waiting for response from prev request.");
return;
}
// this method makes sure we are subscribed only once
this.subscribeToLowLevelSerial();
this.isInSendSyncMode = true;
this.sendSyncCallback = callback;
this.sendSyncActiveId = "cam-install-" + this.sendSyncIdNum;
this.sendSyncIdNum++;
var spjsCmd = "exec";
spjsCmd += " id:" + this.sendSyncActiveId;
if (this.isUseLogin) spjsCmd += " user:" + this.user + " pass:" + this.pass;
spjsCmd += " " + cmd;
chilipeppr.publish("/com-chilipeppr-widget-serialport/ws/send", spjsCmd);
console.log("just did sendSync. sendSyncActiveId:", this.sendSyncActiveId);
},
onSendSyncWsRecv: function(msg) {
console.log("onSendSyncWsRecv. msg:", msg, "sendSyncActiveId:", this.sendSyncActiveId);
if (msg.match(/^\{/)) {
// it's json
var data = $.parseJSON(msg);
//console.log("got json for onSendSyncWsRecv. data:", data);
if ('ExecStatus' in data) {
// this is what we were waiting for
//console.log("onSendSyncWsRecv we have ExecStatus so good. is it our id?", this.sendSyncActiveId);
if (data.ExecStatus == "Progress") {
// just stick in the terminal window
this.appendToOutput(data.Output);
} else {
// we get an ExecStatus of Done or Error here
// see if it's the id we want
if (data.Id == this.sendSyncActiveId) {
console.log("response was for sendSyncActiveId:", this.sendSyncActiveId);
// it is the cmd we expect, awesome
//chilipeppr.unsubscribe("/com-chilipeppr-widget-serialport/ws/recv", this.onSendSyncWsRecv);
this.unsubscribeFromLowLevelSerial();
this.isInSendSyncMode = false;
//console.log("it was our id. we are doing the sendSync callback now with data:", data);
this.sendSyncActiveId = null;
this.sendSyncCallback(data);
//this.sendSyncCallback = null;
}
}
}
}
},
isAreWeSubscribedToLowLevel: false,
subscribeToLowLevelSerial: function() {
// subscribe to websocket events
if (this.isAreWeSubscribedToLowLevel == false) {
chilipeppr.subscribe("/com-chilipeppr-widget-serialport/ws/recv", this, this.onWsRecv);
} else {
console.log("we were asked to subscribe to low-level /ws/recv but already were");
}
},
unsubscribeFromLowLevelSerial: function() {
// unsubscribe to websocket events
chilipeppr.unsubscribe("/com-chilipeppr-widget-serialport/ws/recv", this.onWsRecv);
this.isAreWeSubscribedToLowLevel = false;
},
onWsRecv: function(msg) {
if (msg.match(/^\{/)) {
// it's json
var data = $.parseJSON(msg);
console.log("got json for onWsRecv. data:", data);
if ('ExecStatus' in data) {
//this.appendLog(data.Output + "\n");
/*if (this.isInRaspiCheckMode) {
this.checkIfRaspberryPiCallback(data);
} else */
if (this.isInSendSyncMode) {
this.onSendSyncWsRecv(msg);
}
} else if ('ExecRuntimeStatus' in data) {
this.onExecRuntimeStatus(data);
}
}
},
isInRaspiCheckMode: false,
raspiCapture: "",
isRaspberryPi: false,
checkRaspiUserCallback: null,
checkIfRaspberryPi: function(callback) {
this.checkRaspiUserCallback = callback;
// this.isInRaspiCheckMode = true;
// this.subscribeToLowLevelSerial();
// we potentially have a raspi candidate. send actual cmd line and parse that
var that = this;
this.sendSync('cat /etc/os-release', function(data) {
console.log("got done with 1st step of checkIfRaspberryPi. data:", data);
this.raspiCapture = data.Output;
that.sendSync('echo "done-with-cat-etc-release"', that.checkIfRaspberryPiCallback.bind(that));
});
},
checkIfRaspberryPiCallback: function(payload) {
// analyze what's coming back
if (payload.Output.match(/done-with-cat-etc-release/)) {
// we are done capturing
// this.isInRaspiCheckMode = false;
// this.unsubscribeFromLowLevelSerial();
console.log("done capturing");
//this.appendLog('We captured\n<span style="color:red">' + this.raspiCapture + '</span>');
var status = {
isRaspberryPi: false
};
if (this.raspiCapture.match(/raspbian/i)) {
// looks like we're on a raspi
//this.appendLog("You are running SPJS on a Raspberry Pi.\n");
//this.showAsRaspi();
status.isRaspberryPi = true;
} else {
// It's not raspi
//this.resetAsRaspi();
}
if (this.checkRaspiUserCallback) this.checkRaspiUserCallback(status);
this.raspiCapture = "";
} else {
this.raspiCapture += payload.Output;
}
},
isInCheckLinuxMode: false,
checkLinuxCallback: null,
checkIfLinux: function(callback) {
// we can check if linux by asking for an execruntime status
// subscribe to low-level callback
this.checkLinuxCallback = callback;
this.isInCheckLinuxMode = true;
this.subscribeToLowLevelSerial();
this.sendExecRuntime();
},
execruntime: null,
onExecRuntimeStatus: function(json) {
console.log("got onExecRuntimeStatus. json:", json);
//this.appendLog(JSON.stringify(json) + "\n");
this.execruntime = json;
this.unsubscribeFromLowLevelSerial();
this.isInCheckLinuxMode = false;
if (this.checkLinuxCallback) this.checkLinuxCallback(json);
this.checkLinuxCallback = null;
/*
if (json.OS.match(/linux/i) && json.Arch.match(/arm/i)) {
this.execruntime = json;
//this.checkIfRaspberryPi();
//setTimeout(this.askForPwd.bind(this), 1000);
}
*/
},
isSpjsStatusInitted: false,
statusCallback: null,
checkIfSpjsConnected: function(callback) {
this.statusCallback = callback;
this.requestSpjsStatus();
},
requestSpjsStatus: function() {
// we need to ask spjs to get a version back
if (this.isSpjsStatusInitted == false) {
chilipeppr.subscribe("/com-chilipeppr-widget-serialport/recvStatus", this, this.onRequestSpjsStatusCallback);
this.isSpjsStatusInitted = true;
}
// wait about 2 seconds just to wait a bit for connecting
setTimeout(function() {
chilipeppr.publish("/com-chilipeppr-widget-serialport/requestStatus");
}, 1000);
},
onRequestSpjsStatusCallback: function(payload) {
chilipeppr.unsubscribe("/com-chilipeppr-widget-serialport/recvStatus", this.onRequestSpjsStatusCallback);
this.isSpjsStatusInitted = false;
this.statusCallback(payload);
},
/**
* Attach all events to the install div to enable everything to work.
*/
uv4lSetupInstall: function() {
$('#' + this.id + " .btn-install").click(this.uv4lInstall.bind(this));
$('#' + this.id + " .btn-login").click(this.onHostLogin.bind(this));
},
isUseLogin: false, // if set to true then use login
user: null,
pass: null,
onHostLogin: function() {