-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengine.js
403 lines (277 loc) · 9.05 KB
/
engine.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
var _ = require('lodash'),
R = require('ramda'),
Promise = require('bluebird'),
args = require('minimist')(process.argv.slice(2))
EventEmitter2 = require('eventemitter2').EventEmitter2,
ROSLIB = require('roslib'),
Fiber = require('fibers')
Future = require('fibers/future'),
wait = Future.wait,
Utils = require('./utils'),
process_send2 = Utils.process_send2,
util = require('util'),
request = require('request'),
Requester = require('./requester').Requester,
Resource = require('./requester').Resource,
UUID = require('node-uuid'),
Ros = require('./ros'),
URL = require('url');
/*
* Engine class
*/
var Engine = function(opts){
EventEmitter2.call(this, {wildcard: true});
this.options = _.assign({
ros_retries: 0,
ros_retry_interval: 1000,
}, opts);
var engine = this;
var that = this;
var ros = engine.ros = new Ros(this.options);
ros.on('status.**', function(){
engine.emit(this.event);
});
this.executions = [];
this.topics = [];
this.my_dynamic_resource_ids = []; // dynamic resources id allocated in this engine.
_.defer(function(){
// engine.emit('started');
});
};
util.inherits(Engine, EventEmitter2);
Engine.prototype.socketBroadcast = function(namespace, key, msg){
process_send2({action: 'socket_broadcast', namespace:namespace, key: key, msg: msg})
this.debug('socket broadcast', namespace, key, msg);
};
Engine.prototype.subscribe = function(topic, type, cb){
return this.ros.subscribe(topic, type, cb);
};
Engine.prototype.publish = function(topic, type, msg){
return this.pub(topic, type, msg);
};
Engine.prototype.pub = function(topic, type, msg){
this.ros.publish(topic, type, msg);
return null;
};
Engine.prototype.sleep = function(ms){
var _sleep = function(ms){
var future = new Future;
setTimeout(function(){
future.return();
}, ms);
return future;
};
_sleep(ms).wait();
};
Engine.prototype.runService = function(name, type, request){
var e = this;
var _runService = function(name, type, request){
var future = new Future;
var service = new ROSLIB.Service({
ros : e.ros,
name : name,
servicetype : type
});
var request = new ROSLIB.ServiceRequest(request);
service.callService(request, function(result){
future.return(result);
});
return future;
};
return _runService(name, type, request).wait();
};
Engine.prototype.runCode = function(code){
code = ["var f = Fiber(function(){ try{ ", code , " }catch(error_in_fiber){ console.log('error in fiber', error_in_fiber); throw error_in_fiber }}); f.run(); f"].join("\n");
code = Utils.js_beautify(code);
this.debug("---------------- scripts -----------------");
this.debug(_.map(code.split(/\n/), function(line){ return line; }).join("\n"));
this.debug("------------------------------------------");
try{
var f = eval(code);
this.executions.push(f);
this.log("scripts evaluated.");
}catch(e){
this.log('invalid block scripts. failed. - ' + e.toString());
this.emit('status.error', e.message);
}
};
// public - promise version
Engine.prototype.waitForTopicsReady = function(required_topics){
return this.ros.waitForTopicsReady(required_topics);
};
// private - fiber version
Engine.prototype._waitForTopicsReadyF = function(required_topics){
var engine = this;
var delay = this.options.action_delay;
var fiber = Fiber.current;
var timer = setInterval(function(){
if(!fiber.stopped){
engine.ros.underlying.getTopics(function(topics){
var remapped_topics = R.filter(function(t){ return R.contains(t, required_topics); })(topics);
console.log('topic count check : ', [remapped_topics.length, required_topics.length].join("/"), remapped_topics, required_topics);
if(remapped_topics.length >= required_topics.length){
clearInterval(timer);
setTimeout(function(){
if(!fiber.stopped){
fiber.run();
}else{
fiber.throwInto('stopped');
}
}, delay);
}
});
}else{
clearInterval(timer);
console.log('running fiber will stop');
fiber.throwInto('stopped');
}
}, 1000);
Fiber.yield();
};
Engine.prototype.allocateResource = function(rapp, uri, remappings, parameters, options){
var engine = this;
var allocation_type = options.type || 'dynamic';
var future = new Future();
var key = null;
if(allocation_type == 'static'){
var key = rapp + uri;
}
process_send2({action: 'allocate_resource', key: key, rapp: rapp, uri: uri, remappings: remappings, parameters: parameters, options: options})
.then(function(ctx){
if(allocation_type == 'dynamic')
engine.my_dynamic_resource_ids.push(ctx.req_id);
future.return(ctx);
});
return future.wait();
};
Engine.prototype.releaseResource = function(ctx){
// process_send2({cmd: 'ref_counted_release_resource', ctx: ctx});
return process_send2({cmd: 'release_resource', requester_id: ctx.req_id});
};
Engine.prototype._scheduled = function(rapp, uri, remappings, parameters, topics_count, name, callback){
var engine = this;
var r = new Requester(this);
this.ros.underlying.getTopics(function(topics){
engine.log("topics : ", topics);
var res = new Resource();
res.rapp = rapp;
res.uri = uri;
res.remappings = remappings;
console.log("remapping ", res.remappings);
res.parameters = parameters;
r.send_allocation_request(res).then(function(reqId){
var topics_ready = new Promise(function(resolve, reject){
var timer = setInterval(function(){
engine.ros.underlying.getTopics(function(topics){
var remapped_topics = R.filter(R.match("^"+name))(topics);
console.log('topic count check : ', remapped_topics.length);
if(remapped_topics.length >= topics_count){
clearInterval(timer);
resolve();
}
});
}, 1000);
});
topics_ready.then(function(){
callback(r);
});
});
});
};
Engine.prototype._changeResourceRefCount = function(rid, delta){
delta = delta || 1;
process_send2({cmd: 'change_resource_ref_count', req_id: rid, delta: delta});
};
Engine.prototype.incResourceRefCount = function(rid){
};
Engine.prototype.decResourceRefCount = function(rid){
};
Engine.prototype.runScheduledAction = function(ctx, name, type, goal, onResult, onFeedback){
var name = _.detect(ctx.remappings, {remap_from: name}).remap_to;
var engine = this;
var required_topics = _.map(["feedback", "result", "status"], function(suffix){ return name + "/" + suffix});
engine.log('action : ', ctx, required_topics, name);
engine._waitForTopicsReadyF(required_topics);
this.ros.run_action(name, type, goal,
function(items){
onResult(items);
engine.releaseResource(ctx);
},
function(items){ onFeedback(items) });
};
Engine.prototype.scheduledSubscribe = function(ctx, topic, type, callback){
var name = _.detect(ctx.remappings, {remap_from: topic}).remap_to;
this.ros.subscribe(name, type, callback);
};
Engine.prototype.scheduledPublish = function(ctx, topic, type, msg){
var name = _.detect(ctx.remappings, {remap_from: topic}).remap_to;
this.ros.publish(name, type, msg);
};
Engine.prototype.clear = function(){
var that = this;
// stop fibers
this.executions.forEach(function(f){
f.stopped = true;
});
this.executions = [];
var proms = _.map(this.my_dynamic_resource_ids, function(rid){
return process_send2({cmd: 'release_resource', requester_id: rid});
});
return Promise.all(proms).then(function(){
// that.unsubscribeAll();
that.log('engine cleared');
}).catch(function(e){
that.log('fail - engine clear ' + e.toString());
});;
};
Engine.prototype.print = function(msg){
console.log(new Date().toString() + " - " + msg.green);
};
Engine.prototype.log = function(args){
global.logger.info(args)
};
Engine.prototype.debug = function(args){
global.logger.debug(args);
};
Engine.prototype.itemsToCode = function(items){
var js = _.map(items, function(i){
i = _.isString(i) ? JSON.parse(i) : i;
return "// "+i.title+"\n"+i.js;
}).join("\n\n");
return js;
};
Engine.prototype.runItems = function(items) {
var scripts = this.itemsToCode(items);
this.runCode(scripts);
};
Engine.prototype.getParam = function(k, cb){
var param = new ROSLIB.Param({
ros : this.ros,
name : k
});
param.get(cb)
};
Engine.prototype.setParam = function(k, v, cb){
var paramClient = new ROSLIB.Service({
ros : this.ros,
name : '/rosapi/set_param',
serviceType : 'rosapi/SetParam'
});
var request = new ROSLIB.ServiceRequest({
name : k,
value : JSON.stringify(v)
});
paramClient.callService(request, cb);
};
Engine.prototype.load = function(){
this.runBlocks(null);
};
Engine.prototype.reload = function(){
var that = this;
this.clear();
this.load();
};
Engine.prototype.createUI = function(name, meta){
process_send2({cmd: 'create_ui', name: name, meta: meta});
};
module.exports = Engine;