-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModule.js
1471 lines (1257 loc) · 44.4 KB
/
Module.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
// Constants
const DIR = 'https://localhost:8000/'; // Directory containing resources
const JOINTS = 7; // Numer of joints in Sawyer arm
const VERBOSE = true; // Whether or not to print everything
const BUTTON = {'back': 0, 'show': 1, 'circle': 2, 'square': 3, 'triangle': 4};
// const ROBOT = 'sawyer';
const ROBOT = 'sawyer';
const ARDUINO = 'button_box';
/**
* A learning module for TeachBot.
*
* General interpreter for module JSON files. Loads, parses, and plays instructions.
* Example of how to use:
* >> var m = new Module(1, main, [image,canvas_container]);
* >> async function main() {
* >> m.displayOff();
* >> image.style.display = 'initial';
* >> m.start();
* >> }
*
* @class
*
* @param {number} module_num The module number. Used to find JSON, audio, and text files.
* @param {function} main Function to run when all resources have been loaded.
* @param {Array} content_elements List of all HTML elements that have display properties.
*/
function Module(module_num, main, content_elements) {
if (VERBOSE) console.log(`Beginning Module ${module_num}`);
// Instance Variables
this.module_num = module_num; // The index of the current module. TODO: replace with Claire's naming structure
this.main = main; // The function to run after all resources have been loaded.
this.content_elements = content_elements; // The elements to be loaded. TODO: consider deprecating per Tongxi's suggestion.
this.loaded = {'audio':false, 'text':false, 'json':false}; // Dictionary to track which resources have loaded.
this.drawings = []; // Array of objects to draw on the canvas.
this.graphic_mode = 'image'; // Current graphic mode. See: set_graphic_mode().
this.canvas_frame_req; // Animation frame request. See: set_graphic_mode().
this.button = 'none';
this.program = [];
this.free_mode = false
// Initialize self to module for use in event callbacks
self = this;
/*******************************
* Setup ROS communication *
*******************************/
var ros = new ROSLIB.Ros({ url: 'wss://localhost:9090' });
ros.on('connection', function() { console.log('Connected to websocket server.'); });
ros.on('error', function(error) { console.log('Error connecting to websocket server: ', error); window.alert('Error connecting to websocket server'); });
ros.on('close', function() { console.log('Connection to websocket server closed.'); });
// Publishing topics
this.camera = new ROSLIB.Topic({
ros: ros,
name: '/teachbot/camera',
messageType: 'std_msgs/Bool'
})
// Subscribing topics
this.box_bin = new ROSLIB.Topic({
ros: ros,
name: '/teachbot/box_in_bin',
messageType: 'std_msgs/Bool'
});
this.button_topic = new ROSLIB.Topic({
ros: ros,
name: '/teachbot/button',
messageType: 'std_msgs/String'
});
// this.button_topic.subscribe(self.buttontopicCallback)
this.command_complete = new ROSLIB.Topic({
// Deprecated, but still used by 'camera' and 'camera_off'
ros: ros,
name: '/teachbot/command_complete',
messageType: 'std_msgs/Empty'
})
this.position = new ROSLIB.Topic({
ros: ros,
name: '/teachbot/position',
messageType: ROBOT + '/JointInfo'
});
this.position.subscribe(self.positionCallback);
this.velocity = new ROSLIB.Topic({
ros: ros,
name: '/teachbot/velocity',
messageType: ROBOT + '/JointInfo'
});
this.velocity.subscribe(self.velocityCallback);
this.effort = new ROSLIB.Topic({
ros: ros,
name: '/teachbot/effort',
messageType: ROBOT + '/JointInfo'
});
this.effort.subscribe(self.effortCallback);
this.endpoint = new ROSLIB.Topic({
ros: ros,
name: '/teachbot/EndpointInfo',
messageType: ROBOT + '/EndpointInfo'
});
this.endpoint.subscribe(self.endpointCallback);
// Service Servers
var DevModeSrv = new ROSLIB.Service({
ros: ros,
name: '/teachbot/dev_mode',
serviceType: ROBOT + '/DevMode'
});
DevModeSrv.advertise(this.devRxCallback);
var ButtonReceiverSrv = new ROSLIB.Service({
ros: ros,
name: '/teachbot/buttons',
serviceType: ARDUINO + '/ButtonInfo'
});
ButtonReceiverSrv.advertise(this.buttonCallback);
var PlayAudioSrv = new ROSLIB.Service({
ros: ros,
name: '/teachbot/PlayAudio',
messageType: ROBOT + '/PlayAudio'
});
PlayAudioSrv.advertise(this.playAudioCallback);
// Service Clients
this.SetRobotModeSrv = new ROSLIB.Service({
ros: ros,
name: '/teachbot/set_robot_mode',
serviceType: 'SetRobotMode'
});
this.CuffWaysSrv = new ROSLIB.Service({
ros: ros,
name: '/teachbot/CuffWays',
serviceType: 'CuffWays'
});
this.UpdateAudioDurationSrv = new ROSLIB.Service({
ros: ros,
name: '/teachbot/audio_duration',
serviceType: 'AudioDuration'
});
// Actions
this.CuffInteractionAct = new ROSLIB.ActionClient({
ros: ros,
serverName: '/teachbot/CuffInteraction',
actionName: ROBOT + '/CuffInteractionAction'
});
this.GoToJointAnglesAct = new ROSLIB.ActionClient({
ros: ros,
serverName: '/teachbot/GoToJointAngles',
actionName: ROBOT + '/GoToJointAnglesAction'
});
this.AdjustPoseToAct = new ROSLIB.ActionClient({
ros: ros,
serverName: '/teachbot/AdjustPoseTo',
actionName: ROBOT + '/AdjustPoseToAction'
});
this.GripperAct = new ROSLIB.ActionClient({
ros: ros,
serverName: '/teachbot/Gripper',
actionName: ROBOT + '/GripperAction'
});
this.GoToCartesianPoseAct = new ROSLIB.ActionClient({
ros: ros,
serverName: '/teachbot/GoToCartesianPose',
actionName: ROBOT + '/GoToCartesianPoseAction'
});
this.MultipleChoiceAct = new ROSLIB.ActionClient({
ros: ros,
serverName: '/teachbot/MultipleChoice',
actionName: ROBOT + '/MultipleChoiceAction'
});
this.PickUpBoxAct = new ROSLIB.ActionClient({
ros: ros,
serverName: '/teachbot/PickUpBox',
actionName: ROBOT + '/PickUpBoxAction'
});
this.AdjustPoseByAct = new ROSLIB.ActionClient({
ros: ros,
serverName: '/teachbot/AdjustPoseBy',
actionName: ROBOT + '/AdjustPoseByAction'
});
this.ButtonPressAct = new ROSLIB.ActionClient({
ros: ros,
serverName: '/teachbot/ButtonSend',
actionName: ROBOT + '/ButtonSendAction'
})
this.WaitAct = new ROSLIB.ActionClient({
ros: ros,
serverName: '/teachbot/Wait',
actionName: ROBOT + '/WaitAction'
})
// Initialize dictionary
this.dictionary = {};
//this.getEndpoint();
/*********************
* HTML Elements *
*********************/
this.ctx = canvas_obj.getContext('2d');
canvas_obj.width = window.innerWidth*0.96;
canvas_obj.height = window.innerHeight*0.76;
this.ch = canvas_obj.height/100.0;
this.cw = canvas_obj.width/100.0;
this.robot_color = getComputedStyle(document.body).getPropertyValue('--robot-color')
/************************
* Update Font Size *
************************/
this.textBoxMaxHeight = document.getElementById("adjustable").scrollHeight;
/******************************
* Setup Section Sequence *
******************************/
var jsonPath = DIR + 'js/json/' + this.module_num + '.json';
var jqhxr = $.getJSON(jsonPath, function(data) {
self.sections = data.sections;
for (let s=0; s<self.sections.length; s++) {
self.sections[s]._textLoaded = false;
self.sections[s]._audioLoaded = false;
}
self.loadTextAndAudio();
});
jqhxr.fail(function() {
throw new Error('JSON file not formatted correctly. Go to ' + jsonPath + ' to learn more.')
});
jqhxr.done(function() {
self.loaded['json'] = true;
if (self.allLoaded()) { self.main(); }
});
}
// Callbacks
Module.prototype.buttontopicCallback = function(msg) {
var value = parseInt(msg.data)
console.log('Changing dict value')
self.dictionary['lastButton'] = value;
}
Module.prototype.positionCallback = function(msg) {
for (let j=0; j<Object.keys(msg).length; j++) {
self.dictionary[`JOINT_POSITION_${j}`] = msg[`j${j}`];
}
}
Module.prototype.velocityCallback = function(msg) {
for (let j=0; j<Object.keys(msg).length; j++) {
self.dictionary[`JOINT_VELOCITY_${j}`] = msg[`j${j}`];
}
}
Module.prototype.effortCallback = function(msg) {
for (let j=0; j<Object.keys(msg).length; j++) {
self.dictionary[`EFFORT_${j}`] = msg[`j${j}`];
}
}
Module.prototype.endpointCallback = function(msg) {
self.dictionary[`ENDPOINT_POSITION_X`] = msg.position.x;
self.dictionary[`ENDPOINT_POSITION_Y`] = msg.position.y;
self.dictionary[`ENDPOINT_POSITION_Z`] = msg.position.z;
self.dictionary[`ENDPOINT_ORIENTATION_X`] = msg.orientation.x;
self.dictionary[`ENDPOINT_ORIENTATION_Y`] = msg.orientation.y;
self.dictionary[`ENDPOINT_ORIENTATION_Z`] = msg.orientation.z;
self.dictionary[`ENDPOINT_ORIENTATION_W`] = msg.orientation.w;
}
/*Module.prototype.unsubscribeFrom = function(topic) {
topic.unsubscribe();
topic.removeAllListeners();
switch (topic.name) {
case '/teachbot/position':
topic.subscribe(self.positionCallback);
break;
case '/teachbot/velocity':
topic.subscribe(self.velocityCallback);
break;
case '/teachbot/effort':
topic.subscribe(self.effortCallback);
break;
case '/teachbot/endpoint':
topic.subscribe(self.endpointCallback);
break;
}
}*/
/**
* Loads text and audio.
*/
Module.prototype.loadTextAndAudio = function() {
// Base of directory containing text
this.text_dir = DIR + 'text/module' + this.module_num + '/';
// For each section
for (let s=0; s<this.sections.length; s++) {
// Load all lines in corresponding text file.
jQuery.get(this.text_dir + this.sections[s].id + '.txt', function(data) {
// Load text.
self.sections[s]._textArray = data.split('\n');
self.sections[s]._textLoaded = true;
// Load audio.
var audioCount = self.sections[s]._textArray.length;
// If there are no audio files in this section, mark the section as loaded.
if (audioCount==0) {
self.sections[s]._textLoaded = true;
self.sections[s]._audioLoaded = true;
// Otherwise, load them.
} else {
self.sections[s]._audiofiles_mp3 = new Array(audioCount);
self.sections[s]._audio_duration = new Array(audioCount);
self.sections[s]._audio_duration_copy = new Array(audioCount);
self.sections[s]._num_loaded = 0;
for (let a=0; a<audioCount; a++) {
self.sections[s]._audiofiles_mp3[a] = DIR + 'audio/module' + self.module_num + '/' + self.sections[s].id + '/line' + a.toString() + '.mp3';
let audio = new Audio();
audio.addEventListener('canplaythrough', function() {
self.sections[s]._audio_duration[a] = audio.duration*1000;
self.sections[s]._audio_duration_copy[a] = audio.duration*1000;
self.sections[s]._num_loaded++;
if (self.sections[s]._num_loaded === audioCount) {
self.sections[s]._audioLoaded = true;
for (let ss=0; ss<self.sections.length; ss++) {
if (!self.sections[ss]._audioLoaded || !self.sections[ss]._textLoaded) {
return;
}
}
self.loaded['text'] = true;
self.loaded['audio'] = true;
if (self.allLoaded()) { self.main(); }
}
}, false);
audio.src = self.sections[s]._audiofiles_mp3[a];
}
}
// If all the sections' text and audio files have been loaded, mark it and check to proceed.
for (let ss=0; ss<self.sections.length; ss++) {
if (!self.sections[ss]._audioLoaded || !self.sections[ss]._textLoaded) {
return;
}
}
self.loaded['text'] = true;
self.loaded['audio'] = true;
if (self.allLoaded()) { self.main(); }
});
}
}
/**
* Play audio file.
*
* Plays a given audio file.
*
* @param {string} audioFile URL of audio file.
* @param {number} duration Duration of audio file in milliseconds.
* @param {string} text Text to display on screen while playing audio.
*/
Module.prototype.play = async function(audioFile, duration, text) {
// Play audio.
player.src = audioFile;
player.play();
// Update text on screen.
adjustable.innerHTML = text;
this.adjust_text();
// Convert units of duration from [ms]->[s]
duration/=1000.0;
// Inform robot for how long current audio file will play.
this.UpdateAudioDurationSrv.callService(new ROSLIB.ServiceRequest({audio_duration: duration}), result => {return});
// Log action.
if (VERBOSE) console.log('Playing ' + audioFile + ', duration ' + Math.round(duration) + 's.');
}
/**
* Adjusts the text size to fit in the text box.
*
* Adjusts the font until the text fills the most space possible in the text box or the maximum font size is reached.
*
* @param {string} [max_font_size='64px'] The maximum allowable font size.
*/
Module.prototype.adjust_text = function(max_font_size='64px') {
var resize_me = document.getElementById('adjustable');
resize_me.style.fontSize = max_font_size;
while (resize_me.scrollHeight > this.textBoxMaxHeight && parseInt(resize_me.style.fontSize)>2){
resize_me.style.fontSize = parseInt(resize_me.style.fontSize) - 1 + 'px';
}
}
/**
* Format a GoToJointAngles goal for sending.
*
* When the returned object is sent, the robot should move to the position specified.
*
* @param {[string,Array]} joint_angles Either an Array of joint angles or the name of the specific pose.
* @param {number} [speed_ratio=0] Fraction of maximum speed for the robot to move.
* @param {bool} [wait=false] Tells the robot whether or not to wait for the audio file to be done playing.
* @return {object} ROSLIB.Goal object to be sent.
*/
Module.prototype.getGoToGoal = function(joint_angles, speed_ratio=0, wait=false) {
var goalMessage = {
speed_ratio: speed_ratio,
wait: wait
}
if (typeof joint_angles === 'string') {
goalMessage.name = this.hashTokeyVal(joint_angles);
} else if (joint_angles instanceof Array) {
for (let j=0; j<joint_angles.length; j++) {
goalMessage[`j${j}pos`] = joint_angles[j];
}
} else {
throw 'goToJointAngles instruction incorrectly formatted.';
}
return new ROSLIB.Goal({
actionClient: self.GoToJointAnglesAct,
goalMessage: goalMessage
});
}
Module.prototype.pub_angle = function(angle) {
var req = new ROSLIB.Message({
data: this.hashTokeyVal(angle)
});
this.joint_angle.publish(req);
}
/*
Module.prototype.getEndpoint = function(){
this.endpoint.subscribe(function(message) {
self.dictionary['position_x'] = message.position.x;
self.dictionary['position_y'] = message.position.y;
self.dictionary['position_z'] = message.position.z;
self.dictionary['orientation_x'] = message.orientation.x;
self.dictionary['orientation_y'] = message.orientation.y;
self.dictionary['orientation_z'] = message.orientation.z;
self.dictionary['orientation_w'] = message.orientation.w;
//console.log(self.dictionary)
});
}
*/
/**
* Whether all page resources are loaded.
*
* Returns true iff all the values in self.loaded are true.
*/
Module.prototype.allLoaded = function() {
for (let key in self.loaded) {
if (!self.loaded[key]) {
return false;
}
}
return true;
}
/**
* Hides all elements on page.
*
* Turns the 'display' property of all elements in self.content_elements to 'none'.
* Optionally also clears the canvas.
*
* @param {boolean} [clearCanvas=false] Whether or not to also clear the entire canvas.
*/
Module.prototype.displayOff = function(clearCanvas=false) {
this.content_elements.forEach(function(elem) {
elem.style.display = 'none';
});
if (clearCanvas) {
this.drawings = [];
this.ctx.clearRect(0,0,100*this.cw,100*this.ch);
}
}
/**
* Toggles development mode.
*
* Callback for the DevModeSrv service.
* Turns development mode on if the message is 1, off if 0.
*
* @param {object} req ROS message containing 0 or 1.
* @param {object} resp To be honest, I don't really know why this is an input.
*/
Module.prototype.devRxCallback = function(req, resp) {
switch (req.status) {
case 0:
self.devMode = false
for (let s=0; s<self.sections.length; s++) {
self.sections[s]._audio_duration = self.sections[s]._audio_duration_copy.slice();
}
if (VERBOSE) console.log('Exiting dev mode.');
break;
case 1:
self.devMode = true
for (let s=0; s<self.sections.length; s++) {
for (let d=0; d<self.sections[s]._audio_duration.length; d++) {
self.sections[s]._audio_duration[d] = 0;
}
}
if (VERBOSE) console.log('Entering dev mode.');
break;
}
resp['success'] = true;
resp['message'] = 'Set successfully';
return true;
}
/**
*
*/
Module.prototype.playAudioCallback = function(req, resp) {
player.src = DIR + 'audio/' + req.filename;
let audio = new Audio();
audio.addEventListener('canplaythrough', function() {
player.play();
}, false);
audio.src = player.src;
return true;
}
/**
* Coordinate transform from robot-space to
*/
Module.prototype.robot2canvas = async function(x, y, robot='sawyer') {
const Kx = 72.73;
const bx = 51.45;
const Ky = 157.89;
const by = -30;
switch (robot) {
case 'sawyer':
x_canvas = (Kx * y + bx) * this.cw;
y_canvas = (Ky * x + by) * this.ch;
default:
throw `Robot ${robot} not supported.`;
}
return {
x: x_canvas,
y: y_canvas
};
}
/**
* Detects if button was pressed
* If the switch value changes, it toggles development mode
*
* Callback for the ButtonReceiverSrv service.
* Turns development mode on if the message is 'On', off if 'Off'.
* Also detects if a button was pressed and changes the value of this.button
*
* @param {object} req ROS message in the form of a string
* @param {object} resp A string confirming that the button was received
*/
Module.prototype.buttonCallback = function(req, resp) {
switch (req.button) {
case 'Off':
self.devMode = false
for (let s=0; s<self.sections.length; s++) {
self.sections[s]._audio_duration = self.sections[s]._audio_duration_copy.slice();
}
resp['response'] = 'Exiting dev mode';
if (VERBOSE) console.log('Exiting dev mode.');
break;
case 'On':
self.devMode = true
for (let s=0; s<self.sections.length; s++) {
for (let d=0; d<self.sections[s]._audio_duration.length; d++) {
self.sections[s]._audio_duration[d] = 0;
}
}
resp['response'] = 'Entering dev mode';
if (VERBOSE) console.log('Entering dev mode.');
break;
default:
self.button = parseInt(req.button)
resp['response'] = 'Button pressed';
}
return true;
}
/**
* Runs a command from the JSON file.
*
* Finds a command from a given address in the JSON file and performs it, then advances to the next command.
* The command address should be formatted as an array with the following elements:
* 0: {string} Name of section.
* 1: {number} Index of instruction within section.
* The following elements are only valid if the instruction is of type 'if' or 'while', and may proceed indefinitely:
* If the parent instruction is of type 'if':
* n : {boolean} Whether to follow the 'if_true' or 'if_false' instructions next.
* n+1: {number} Index of the child instruction.
* Else if the parent instruction is of type 'while':
* n : {number} Index of the child instruction.
*
* @param {Array} [instructionAddr=['intro',0]] Address of instruction to play.
*/
Module.prototype.start = async function(instructionAddr=['intro',0]) {
this.thisSection;
for (let s=0; s<this.sections.length; s++) {
if (this.sections[s].id === instructionAddr[0]) {
this.thisSection = this.sections[s];
break;
}
}
if (this.thisSection === undefined) {
throw `There is no section with id ${instructionAddr[0]}`;
}
var instructions = this.thisSection.instructions;
this.instructionSets = [JSONcopy(instructions)];
if (instructionAddr.length == 1) {
console.log('Reached End of Module.');
return;
}
var instr = instructions[instructionAddr[1]];
for (let instructionAddrLevel=2; instructionAddrLevel<instructionAddr.length; instructionAddrLevel++) {
if (instr.type === 'if') {
instructionAddrLevel++;
if (instructionAddr[instructionAddrLevel-1]) {
instructions = instr.if_true;
} else {
instructions = instr.if_false;
}
} else if (instr.type === 'while') {
instructions = instr.instructions;
} else {
throw `Compound instruction addressing not available for instructions of type ${instr.type}`;
}
this.instructionSets.push(JSONcopy(instructions));
instr = instructions[instructionAddr[instructionAddrLevel]];
}
if (instr.hasOwnProperty('skippable') && instr.skippable && self.devMode) {
this.start(this.getNextAddress(instructionAddr));
} else {
switch(instr.type) {
case 'pause':
console.log("module paused here.")
// self.start(self.getNextAddress(instructionAddr));
break;
// case 'shadow':
// const Kx = 72.73;
// const bx = 51.45;
// const Ky = 157.89;
// const by = -30;
// this.endpoint.subscribe(async function(message) {
// self.ctx.clearRect(0,0,100*self.cw,100*self.ch);
// var x_center = Kx * message.position.y + bx;
// var y_center = Ky * message.position.x + by;
// draw_ball(self.ctx, x_center, y_center, 8, '#7c2629');
// });
// this.pressed.subscribe(async function(message) {
// if (VERBOSE) console.log('Pressed: ' + message.data);
// if (message.data == true) {
// self.endpoint.unsubscribe();
// self.endpoint.removeAllListeners();
// self.pressed.unsubscribe();
// self.pressed.removeAllListeners();
// self.displayOff();
// self.start(self.getNextAddress(instructionAddr));
// }
// });
// break
case 'adjustPoseBy':
checkInstruction(instr, ['geometry', 'axis', 'amount'], instructionAddr);
var goal_AdjustPoseBy = new ROSLIB.Goal({
actionClient: this.AdjustPoseByAct,
goalMessage: {
geometry: this.hashTokeyVal(instr.geometry),
axis: this.hashTokeyVal(instr.axis),
amount: this.hashTokeyVal(instr.amount)
}
});
goal_AdjustPoseBy.on('result', function(result){
self.start(self.getNextAddress(instructionAddr));
});
goal_AdjustPoseBy.send()
break;
case 'adjustPoseTo':
checkInstruction(instr, ['geometry', 'axis', 'amount'], instructionAddr);
var goal_AdjustPoseTo = new ROSLIB.Goal({
actionClient: this.AdjustPoseToAct,
goalMessage:{
geometry: this.hashTokeyVal(instr.geometry),
axis: this.hashTokeyVal(instr.axis),
amount: this.hashTokeyVal(instr.amount)
}
});
goal_AdjustPoseTo.on('result', function(result){
self.start(self.getNextAddress(instructionAddr));
});
goal_AdjustPoseTo.send()
break;
case 'draw':
this.draw(instr, instructionAddr);
break;
case 'LOG':
console.log(Object.keys(instr.aDict))
for (var key in (instr.aDict)) {
console.log('individual key: '+key)
}
this.start(this.getNextAddress(instructionAddr));
break;
case 'buttons':
var goal_ButtonPress = new ROSLIB.Goal({
actionClient: this.ButtonPressAct,
goalMessage:{press: true}
});
goal_ButtonPress.on('result', function(result) {
if (VERBOSE) console.log(self.button)
self.start(self.getNextAddress(instructionAddr));
});
goal_ButtonPress.send();
break;
case 'camera':
var req = new ROSLIB.Message({
data: true
});
console.log('Getting camera info')
this.camera.publish(req);
this.box_bin.subscribe(async function(message) {
if (VERBOSE) console.log('Box success: ' + message.data);
if (message.data == true) {
wheel_val = 1
if (instr.hasOwnProperty('store_answer_in')) {
self.dictionary[instr.store_answer_in] = wheel_val;
}
self.box_bin.unsubscribe();
self.box_bin.removeAllListeners();
self.start(self.getNextAddress(instructionAddr));
} else{
wheel_val = 2
if (instr.hasOwnProperty('store_answer_in')) {
self.dictionary[instr.store_answer_in] = wheel_val;
}
self.box_bin.unsubscribe();
self.box_bin.removeAllListeners();
self.start(self.getNextAddress(instructionAddr));
}
});
break;
case 'camerabw_graphic':
var cv_image_url = DIR + 'images/cv_1.png';
var bw_image = new Image();
bw_image.onload = function() {
console.log('Displaying camera')
self.ctx.drawImage(bw_image, 300, 10, self.ctx.canvas.width*.7, self.ctx.canvas.height)
self.start(self.getNextAddress(instructionAddr));
};
bw_image.src = cv_image_url;
break;
case 'camera_color_graphic':
var cv_image_url = DIR + 'images/cv_2.png';
var color_image = new Image();
color_image.onload = function() {
console.log('Displaying camera')
self.ctx.drawImage(color_image, 300, 10, self.ctx.canvas.width*.7, self.ctx.canvas.height)
self.start(self.getNextAddress(instructionAddr));
};
color_image.src = cv_image_url;
break;
case 'camera_off':
var req = new ROSLIB.Message({
data: false
});
console.log('Shutting down camera')
this.camera.publish(req);
this.command_complete.subscribe(function(message) {
self.command_complete.unsubscribe();
self.command_complete.removeAllListeners();
self.start(self.getNextAddress(instructionAddr));
});
break;
case 'check_pickup':
var goal_PickUpBox = new ROSLIB.Goal({
actionClient: this.PickUpBoxAct,
goalMessage:{check: true}
});
goal_PickUpBox.on('result', function(result){
if (VERBOSE) console.log('Picked up: ' + result);
if (result.is_picked == true) {
wheel_val = 1
if (instr.hasOwnProperty('store_answer_in')) {
self.dictionary[instr.store_answer_in] = wheel_val;
}
self.start(self.getNextAddress(instructionAddr));
} else{
wheel_val = 2
if (instr.hasOwnProperty('store_answer_in')) {
self.dictionary[instr.store_answer_in] = wheel_val;
}
self.start(self.getNextAddress(instructionAddr));
}
});
goal_PickUpBox.send();
break;
case 'clearRect':
this.ctx.clearRect(0,0,100*m.cw,100*m.ch);
this.start(this.getNextAddress(instructionAddr));
break;
case 'complete_program':
action = self.program[0]
console.log(self.program[0])
if (self.program[0] == 'Open Gripper'){
var goal_Gripper2 = new ROSLIB.Goal({
actionClient: this.GripperAct,
goalMessage:{grip: false}
});
goal_Gripper2.on('result', function(result){
console.log('Completed program')
self.program.shift()
if (self.program.length == 0){
self.dictionary['q'] = true;
}
self.start(self.getNextAddress(instructionAddr));
});
goal_Gripper2.send();
} else if (self.program[0] == 'Close Gripper'){
var goal_Gripper1 = new ROSLIB.Goal({
actionClient: this.GripperAct,
goalMessage:{grip: true}
});
goal_Gripper1.on('result', function(result){
console.log('Completed program')
self.program.shift()
if (self.program.length == 0){
self.dictionary['q'] = true;
}
self.start(self.getNextAddress(instructionAddr));
});
goal_Gripper1.send();
} else {
var goal;
goal = this.getGoToGoal('waypoints.pop(0)', 0.25);
goal.on('result', function(result) {
console.log('Completed program')
self.program.shift()
if (self.program.length == 0){
self.dictionary['q'] = true;
}
self.start(self.getNextAddress(instructionAddr));
});
goal.send();
}
break;
case 'cuff_interaction':
checkInstruction(instr, ['ways'], instructionAddr);
var orient_bw_url = DIR + 'images/orientation_bw.png';
var orient_color_url = DIR + 'images/orientation_color.png';
var position_bw_url = DIR + 'images/position_bw.png';
var position_color_url = DIR + 'images/position_color.png';
this.button_topic.subscribe(async function(message) {
var value = parseInt(message.data)
if (value == 6){
draw_pos_orien(self.ctx,3,300,400,position_color_url,position_bw_url, orient_color_url, orient_bw_url,'pos');
if (VERBOSE) console.log('Entering position mode');
self.set_robot_mode({
'mode':'interaction ctrl',
'position_only':false,
'position_x': true,
'position_y': true,
'position_z': false,
'orientation_x': false,
'orientation_y': false,
'orientation_z': false,
'in_end_point_frame': false}, instructionAddr);
} else if (value == 7){
draw_pos_orien(self.ctx,3,300,400,position_color_url,position_bw_url, orient_color_url, orient_bw_url,'orien');
if (VERBOSE) console.log('Entering orientation mode');
self.set_robot_mode({
'mode':'interaction ctrl',
'position_only':false,
'position_x': false,
'position_y': false,
'position_z': false,
'orientation_x': false,
'orientation_y': false,
'orientation_z': true,
'in_end_point_frame': true}, instructionAddr);
} else{
if (VERBOSE) console.log('Received indication to advance');
if (instr.ways == true) {
// self.CuffWaysSrv.callService(new ROSLIB.ServiceRequest({request: true}), result => {return})
self.set_robot_mode({
'mode':'position',
'ways':true}, instructionAddr);
} else {
self.set_robot_mode({
'mode':'position'}, instructionAddr);
}
self.ctx.clearRect(3, 300, 403, 1100)
self.button_topic.unsubscribe();
self.button_topic.removeAllListeners();
self.start(self.getNextAddress(instructionAddr));
}
});
break;
this.button_topic.subscribe(async function(message) {
if (VERBOSE) console.log('Received indication to advance');
for (topic in instr.topics){
eval('self.'+topic+'.unsubscribe();');
eval('self.'+topic+'.removeAllListeners();');
self.button_topic.unsubscribe();
self.button_topic.removeAllListeners();
self.displayOff();
self.start(self.getNextAddress(instructionAddr));
}
});
break;
case 'drawPosOrien':
var orient_bw_url = DIR + 'images/orientation_bw.png';
var orient_color_url = DIR + 'images/orientation_color.png';
var position_bw_url = DIR + 'images/position_bw.png';
var position_color_url = DIR + 'images/position_color.png';
draw_pos_orien(self.ctx,3,300,400,position_color_url,position_bw_url, orient_color_url, orient_bw_url)
this.start(self.getNextAddress(instructionAddr));
break;
case 'encode':